问题描述
我需要从的grep
分配结果,例如数组...
I need to assign the results from a grep
to an array... for example
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
什么是将它们分配给一个bash数组最简单的方法?如果我只是将它们分配给一个变量他们成为一个空格分隔字符串。
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.
推荐答案
要分配输出到一个数组,你需要使用数组赋值的内部命令替换。
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/:.*//'))
内$()运行命令而外部()导致的输出是一个数组。与此问题是,它不会与含有空格的文件的工作。为了解决这个问题,你可以设置IFS为\\ n
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'
arr=($(grep -n "search term" file.txt | sed 's/:.*//'))
unset IFS
您还可以切出的需要由阵列中的每个元素执行一个扩展的sed
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[@]%%:*}")
这篇关于如何将命令的输出分配到一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!