Home > Back-end >  How can turn a multiline string into arrays and echo a specific index value with bash?
How can turn a multiline string into arrays and echo a specific index value with bash?

Time:04-28

bash --version: GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

my multiline var contains this string

item1 item2 item3 item4
item1 item2 item3 item4
item1 item2 item3 item4

I am trying to output item3 (eventually use it for an API call but just echo it for now) as such:

item3
item3
item3

This is how I'm attempting to do it:

while IFS= read -r line
do
    printf "${line[2]}"
done < <(printf '%s\n' "$multiline")

I currently get nothing. Indicating (to me at least) that printf is not getting an array. But when I loop with something like this:

while IFS= read -r line
do
    for item in ${line[@]}
    do
        echo "$item"
    done
done < <(printf '%s\n' "$EC2")

It does echo all 12 items on separate lines as if $line was a legitimate array. I just want item3 of each line.

CodePudding user response:

$ var='item1 item2 item3 item4
item1 item2 item3 item4
item1 item2 item3 item4'

$ echo "$var" | cut -d' ' -f3
item3
item3
item3

or if you prefer:

$ while read -r _ _ foo _; do
    echo "$foo"
done <<< "$var"
item3
item3
item3

or given your command:

aws api call | cut -d' ' -f3

or:

while read -r _ _ foo _; do
    echo "$foo"
done < <(aws api call)

or:

readarray -d $'\n' -t arr < <(aws api call)
printf '%s\n' "${arr[@]}" | cut -d' ' -f3

etc....

CodePudding user response:

Similar to the cut -d' ' -f3 approach but using awk:

$ echo 'item1 item2 item3 item4
item1 item2 item3 item4
item1 item2 item3 item4' | awk '{print $3}'

item3
item3
item3
  • Related