3

With regards to this question (Put line seperated grep result into array), when I use

echo v1.33.4 | arr=($(egrep -o '[0-9]{1,3}'))

with GNU bash, version 5.0.2(1)-release (x86_64-apple-darwin18.2.0) on macOS

I get have an empty array arr in return for

echo "($arr)"
()

then the expected output

1
33
4

What do I do wrong here?

Til Hund
  • 1,543
  • 5
  • 21
  • 37

2 Answers2

1

It wouldn't work with the syntax you have. You are not populating the array with the result of grep. You are not handling the string passed over the pipe and populating an empty array at the received end of the pipe.

Perhaps you were intending to do

array=($(echo v1.33.4 | egrep -o '[0-9]{1,3}'))

Notice how the echo of the string is passed over to the standard input of egrep which was missing in your attempt.

But as in the linked answer, using mapfile would be the best option here because with the above approach if the search results contains words containing spaces, they would be stored in separated indices in the array rather than in a single one.

mapfile -t array < <(echo "v1.33.4" |  egrep -o '[0-9]{1,3}')
printf '%s\n' "${array[@]}"

Notice the array expansion in bash takes the syntax of "${array[@]}" and not just a simple "${array}" expansion.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • Hi Inian, thank you very much. It functions. Do you know how to populate the array in more sophisticated command like in my other question here: https://stackoverflow.com/questions/55137242/bash-get-a-list-of-dates-for-every-saturday-on-a-given-year – Til Hund Mar 13 '19 at 13:49
1

Messed with it a bit and this seems to work:

$ arr=$(echo "v1.33.4" |  egrep -o '[0-9]{1,3}')
$ echo $arr
1 33 4
$ echo "($arr)"
(1
33
4)
notbrain
  • 3,366
  • 2
  • 32
  • 42