KarthickGanesan
KarthickGanesan

Reputation: 11

How to parse my bash output into an array?

The output of my bash command is something like this

["Name1","Name2"]

I need to parse this information into an array with Name1 being the array value 1 and Name2 being the array value 2.

I have tried doing the following:

var1="/bin/curl http://localhost:8083/names"
$var1

yields the following output:

["Name1","Name2"]

And then I tried this to convert the var1 variable into an array

my_array=( $(var1) )

It doesn't work.

After putting the results into var1, I need to convert them into array. How can I do that?

Upvotes: 0

Views: 2939

Answers (5)

Léa Gris
Léa Gris

Reputation: 19555

To be safe with values containing special characters (newlines, tabs...) and parsing your server's answer with jq. You can use a null delimited output:

#!/usr/bin/env bash

get_names() {
  curl http://localhost:8083/hames
}

# fill my_array from null delimited values returned by jq
mapfile -d '' my_array < <(
  get_names |
    jq --join-output '.[]+"\u0000"' # output null delimited array values
)

# debug print my_array values
for i in "${!my_array[@]}"; do
  printf 'my_array[%d]=%q\n' "$i" "${my_array[$i]}"
done

Upvotes: 1

chepner
chepner

Reputation: 531165

Assuming none of the names can contain a newline,

get_names () {
    curl http://localhost:8083/names
}

readarray -a my_array < <(get_names | jq -r '.[]')

Upvotes: 1

1218985
1218985

Reputation: 8012

You can also try the below approach:

arr=( $(echo '["Name1","Name2"]' | sed 's/[][]//g' | sed 's/"//g') )
for i in "${arr[@]}"; do echo $i; done

Here, replace echo '["Name1","Name2"]' with echo $var1, so it would be like:

arr=( $(echo $var1 | sed 's/[][]//g' | sed 's/"//g') )
for i in "${arr[@]}"; do echo $i; done

echo "${arr[0]}" # will hold the value Name1
echo "${arr[1]}" # will hold the value Name2

Upvotes: 0

shellter
shellter

Reputation: 37278

This worked for me

var1='["Name1","Name2"]'
my_array=( $( echo '["Name1","Name2"]' | sed 's/[][,]/ /g') )
echo ${my_array[@]}
echo "${my_array[1]}"
echo "${my_array[0]}"

output

"Name1" "Name2"
"Name2" 
"Name1"

IHTH

Upvotes: 0

Benjamin W.
Benjamin W.

Reputation: 52142

You could do some character fiddling and try to extract the strings like that, but it would be brittle. Instead, I recommend you use a tool that can parse JSON such as jq:

read -d '\t' -a my_array <<< "$(curl http://localhost:8083/names | jq -r '@tsv')"

This reads a tab separated line, as produced by the @tsv filter, into the my_array array.

Upvotes: 0

Related Questions