How do I assign the output of a command into an array?

ceiling cat picture ceiling cat · Feb 26, 2012 · Viewed 97.8k times · Source

I need to assign the results from a grep to an array... for example

grep -n "search term" file.txt | sed 's/:.*//'

This resulted in a bunch of lines with line numbers in which the search term was found.

1
3
12
19

What's the easiest way to assign them to a bash array? If I simply assign them to a variable they become a space-separated string.

Answer

jordanm picture jordanm · Feb 26, 2012

To assign the output of a command to an array, you need to use a command substitution inside of an array assignment. For a general command command this looks like:

arr=( $(command) )

In the example of the OP, this would read:

arr=($(grep -n "search term" file.txt | sed 's/:.*//'))

The inner $() runs the command while the outer () causes the output to be an array. The problem with this is that it will not work when the output of the command contains spaces. To handle this, you can set IFS to \n.

IFS=$'\n' arr=($(grep -n "search term" file.txt | sed 's/:.*//'))

You can also cut out the need for sed by performing an expansion on each element of the array:

arr=($(grep -n "search term" file.txt))
arr=("${arr[@]%%:*}")