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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/questions/55137242/…
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)

1 Comment

Thank you, Brian, for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.