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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9449417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:41:55  来源:igfitidea点击:

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

arraysbashcommand-substitution

提问by ceiling cat

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

我需要将结果从 a 分配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 数组的最简单方法是什么?如果我只是将它们分配给一个变量,它们就会变成一个以空格分隔的字符串。

回答by jordanm

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 commandthis looks like:

要将命令的输出分配给数组,您需要在数组分配中使用命令替换。对于一般命令,command这看起来像:

arr=( $(command) )

In the example of the OP, this would read:

在 OP 的示例中,这将显示为:

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

回答by Shiplu Mokaddim

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 $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"

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