[英]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
的结果分配给一个数组......例如
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?将它们分配给 bash 数组的最简单方法是什么? If I simply assign them to a variable they become a space-separated string.
如果我只是将它们分配给一个变量,它们就会变成一个以空格分隔的字符串。
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:对于一般命令
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
IFS
to \\n
.要处理此问题,您可以将
IFS
设置为\\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:您还可以通过对数组的每个元素执行扩展来消除对 sed 的需要:
arr=($(grep -n "search term" file.txt))
arr=("${arr[@]%%:*}")
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"
find . -printf "\\"%p\\"\\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.