如何将命令的输出分配到数组中?

我需要将来自 grep的结果分配给一个数组... ... 例如

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

这会产生一系列行号的行,在这些行中可以找到搜索词。

1
3
12
19

将它们分配到 bash 数组最简单的方法是什么?如果我简单地将它们赋给一个变量,它们就会变成一个空格分隔的字符串。

114257 次浏览

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"

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[@]%%:*}")