Carlos Caravaca
Carlos Caravaca

Reputation: 13

Convert python list to bash array

I have a python list as a string with the following structure:

var="["127.0.0.1:14550","127.0.0.1:14551"]"

I would like to turn the string into a bash array to be able to loop through it with bash:

for ip in ${var[@]}; do

something

done

Upvotes: 1

Views: 1079

Answers (2)

Timur Shtatland
Timur Shtatland

Reputation: 12415

Use Perl to parse the Python output, like so (note single quotes around the string, which contains double quotes inside):

array=( $( echo '["127.0.0.1:14550","127.0.0.1:14551"]' | perl -F'[^\d.:]' -lane 'print for grep /./, @F;' ) )
echo ${array[*]}

Output:

127.0.0.1:14550 127.0.0.1:14551

Alternatively, use jq as in the answer by 0stone0, or pipe its output through xargs, which removes quotes, like so:

array=( $( echo '["127.0.0.1:14550","127.0.0.1:14551"]' | jq -c '.[]' | xargs ) )

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.
-F'[^\d.:]' : Split into @F on any chars other than digit, period, or colon, rather than on whitespace.

print for grep /./, @F; : take the line split into array of strings @F, select with grep only non-empty strings, print one per line.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

Upvotes: 2

0stone0
0stone0

Reputation: 44162

One option is to treat the string as , and use to parse it:

jq -rc '.[]' <<< '["127.0.0.1:14550","127.0.0.1:14551"]' | while read i; do
    echo $i
done

127.0.0.1:14550

127.0.0.1:14551

Upvotes: 2

Related Questions