Reputation: 1
I tried to loop comma separated values with space, but not able to get the exact value since it has space in the string.
I tried in different ways, but i not able to get desired results. Can anyone help me on this
#!/bin/ksh
values="('A','sample text','Mark')"
for i in `echo $values | sed 's/[)(]//g' | sed 's/,/ /g'`
do
echo $i
done
My expected output is:
A
sample text
Mark
Upvotes: 0
Views: 4823
Reputation: 20002
You should use the single quotes for splitting the string (and quote "$values"
).
When your sed
supports \n
for replacement into a line, you can do without a loop:
echo "${values}" | sed "s/[)(]//g;s/','/\n/g;s/'//g"
# or
sed "s/[)(]//g;s/','/\n/g;s/'//g" <<< "${values}"
When the values in your string are without a comma and parentheses, you can use
grep -Eo "[^',()]*" <<< "${values}"
Better is looking for fields between 2 single quotes and remove those single quotes.
grep -Eo "'[^']*'" <<< "${values}" | tr -d "'"
Upvotes: 0
Reputation: 1040
Simply trim the quotes
#!/bin/ksh
values="('A','sample text','Mark')"
echo $values | tr -d "()'\"" | tr ',' '\n'
output:
A
sample text
Mark
Upvotes: 0
Reputation: 8406
This is the same as Chepner's answer, only kludgier, (variable substitution), and more dangerous, (the eval
...), the better to use the OP's exact $values
assignment:
values="('A','sample text','Mark')"
eval values=${values//,/ }
for i in "${values[@]}"; do
echo "$i"
done
It works in ksh
, but really, if at all possible try to use Chepner's simpler and safer $values
assignment.
Upvotes: 0
Reputation: 531075
First, change values
to an array. Then iterating over it is a simple matter.
values=(A "sample text" Mark)
for i in "${values[@]}"; do
echo "$i"
done
Upvotes: 2