Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 857
ceiling cat Avatar asked Feb 26 '12 00:02

ceiling cat


People also ask

How do you store the output of a command in an array?

to store the output of command <command> into the array my_array . Now the length is stored in my_array_length . What if the output of $(command) has spaces and multiple lines with spaces? I added "$(command)" and it places all output from all lines into the first [0] element of the array.

How do you assign the output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...]

How can I store the find command results as an array in Bash?

In bash, $(<any_shell_cmd>) helps to run a command and capture the output. Passing this to IFS with \n as delimiter helps to convert that to an array. Benjamin W. This will get only the first file of the results of find into the array.


Video Answer


2 Answers

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[@]%%:*}") 
like image 181
jordanm Avatar answered Sep 28 '22 05:09

jordanm


Space-separated strings are easily traversable in bash.

# save the ouput output=$(grep -n "search term" file.txt | sed 's/:.*//')  # iterating by for. for x in $output; do echo $x; done;  # awk echo $output | awk '{for(i=1;i<=NF;i++) print $i;}'  # convert to an array ar=($output) echo ${ar[3]} # echos 4th element 

if you are thinking space in file name use find . -printf "\"%p\"\n"

like image 30
Shiplu Mokaddim Avatar answered Sep 28 '22 05:09

Shiplu Mokaddim