0

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
2
  • Unless you are getting values from somewhere else, you should make it a regular array: values=(A "sample text" Mark). If you are getting it from somewhere else, have them send an easier-to-parse format, like JSON. Commented Feb 13, 2019 at 13:21
  • 1
    Your values value is not a comma separated. It's a literal string that also contains " and ( and ' and ) Commented Feb 13, 2019 at 13:22

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

8 Comments

how can I change to array ?
values=('A','sample text','Mark') how i will convert this comma seperated values to array ?
lose the comma ,. values=('A' 'sample text' 'Mark')
@Gowtham Your current value is a string that looks an array with commas. This answer uses the array assignment syntax (note the lack of quotes; a=(...) is a special kind of assignment.)
i cant able to loop with this single quote value values=('A' 'sample text' 'Mark'). how can i loop this ?
|
0

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.

Comments

0

Simply trim the quotes

#!/bin/ksh

values="('A','sample text','Mark')"
echo $values |  tr  -d "()'\"" | tr ',' '\n'

output:

A
sample text
Mark

Comments

0

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 "'"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.