Bash Assign Find Output To Array

To assign the output to an array, you need to use a command substitution inside of an array assignment.

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 with files containing spaces. To handle this, you can set IFS to \n.

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

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))
This entry was posted in Linux and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *