Home > OS >  Loop through a comma-separated python-format list
Loop through a comma-separated python-format list

Time:05-05

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.

CodePudding user response:

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

CodePudding user response:

As this question is tagged

You could use csv bash plugin:

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

enable -f /usr/lib/bash/csv csv

csv -a myarray "${string//[][]/,}"

printf "%s\n" "${myarray[@]:1}"
A
B
C,D
E F

Explanation:

  • ${string//[][]/,} will translate both square bracket ] and [ into comas ,.
  • so csv will parse line into $myarray adding a 1st field containing Business_Unit= and a trailing empty field.

To be correct, for avoiding last empty field you'd better use:

printf "%s\n" "${myarray[@]:1:${#myarray[@]}-2}"
A
B
C,D
E F

CodePudding user response:

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
  • Related