Loop through a comma-separated python-format list

Viewed 93

I have bash script with a variable storing values in sort of a python-list format :

Business_Unit=["A","B","C,D","E F"]

and need to loop over to get:

A
B
C,D
E F

The script should keep the commas, spaces and any special characters within the double quotes. I've tried using sed, IFS but it was splitting the line for commas within a string too.

3 Answers

If sed is an option, you can try;

$ sed s'/[][]\|\("\),/\1/g;s/""/\n/g;s/"//g' <<< $Business_Unit
A
B
C,D
E F

Or, if you need to transform the variable first so the quotes exist, you can try;

$ sed 's/\([A-B]\)\(,\)/"\1"\2/g;s/\([A-Z]\(,\| \)\?[A-Z]\)/"&"/g;s/[][]\|\("\),/\1/g;s/""/\n/g;s/"//g' <<< $Business_Unit
A
B
C,D
E F

Sed does it for me:

echo "$Business_Unit" |
sed 's/^[^"]*"//;s/"\]//;s/","/\n/g' |
#    ----------- ------- ----------
#       |           |        |
#       |           |       substitute "," by a new line
#       |          remove the last quotes and ]
#       remove everything upto and including the first " 
while read line ; do
    echo "$line"
done
string='Business_Unit=["A","B","C,D","E F"]'
awk -F\" '{for(i=2; i<=NF; i+=2) print $(i)}' <<< $string
A
B
C,D
E F
Related