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

时间:2021-03-16 13:56:51

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

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

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.

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

2 个解决方案

#1


96  

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.

内部的$()运行命令,而外部的()使输出成为一个数组。这样做的问题是它不能处理包含空格的文件。要处理这个问题,可以将IFS设置为\n。

IFS=$'\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:

还可以通过对数组中的每个元素执行扩展来减少对sed的需要:

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

#2


4  

Space-separated strings are easily traversable in bash.

空格分隔的字符串在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 $out | awk '{for(i=1;i<=NF;i++) print $i;}'

# convert to an array
ar=($out)
echo ${ar[3]} # echos 4th element

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

如果您正在考虑文件名中的空格,请使用find。printf“\”% p \“\ n”

#1


96  

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.

内部的$()运行命令,而外部的()使输出成为一个数组。这样做的问题是它不能处理包含空格的文件。要处理这个问题,可以将IFS设置为\n。

IFS=$'\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:

还可以通过对数组中的每个元素执行扩展来减少对sed的需要:

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

#2


4  

Space-separated strings are easily traversable in bash.

空格分隔的字符串在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 $out | awk '{for(i=1;i<=NF;i++) print $i;}'

# convert to an array
ar=($out)
echo ${ar[3]} # echos 4th element

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

如果您正在考虑文件名中的空格,请使用find。printf“\”% p \“\ n”