bash grep 输出到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7180082/
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
grep output into array
提问by newbietester
Guys How can I make this work
伙计们 我怎样才能使这项工作
`find /xyz/abc/music/ |grep def`
`找到/xyz/abc/music/ |grep def`
I don't want to store the array in any temporary variable. How can we directly operate on this array.
我不想将数组存储在任何临时变量中。我们如何直接对这个数组进行操作。
so to get the 1st element of that array
所以要获得该数组的第一个元素
echo ${$(`find /xyz/abc/music/ |grep def`)[0]} Please help me How I can achieve this
echo ${$(`find /xyz/abc/music/ |grep def`)[0]} 请帮助我如何实现
采纳答案by Micha? Trybus
If you just need the first element (or rather line), you can use head
:
如果您只需要第一个元素(或者更确切地说是行),您可以使用head
:
`find /xyz/abc/music/ |grep def | head -n 1`
If you need access to arbitrary elements, you can store the array first, and then retrieve the element:
如果需要访问任意元素,可以先存储数组,然后检索元素:
arr=(`find /xyz/abc/music/ |grep def`)
echo ${arr[n]}
but this will not put each line of grep output into a separate element of an array.
但这不会将每一行 grep 输出放入一个单独的数组元素中。
If you care for whole lines instead of words, you can use head
and tail
for this task, like so:
如果您关心整行而不是单词,则可以使用head
andtail
完成此任务,如下所示:
`find /xyz/abc/music/ |grep def | head -n line_number | tail -n 1`
回答by Ray Toal
Put the call to find in array brackets
将调用 find 放在数组括号中
X=( $(find /xyz/abc/music/ | grep def) )
echo ${X[1]}
echo ${X[2]}
echo ${X[3]}
echo ${X[4]}
回答by Markus Natter
Even though a bit late, the best solution should be the answer from Ray, but you'd have to overwrite the default field separator environment variable IFS to newline for taking complete lines as an array field. After filling your array, you should switch IFS back to the original value. I'll expand Rays solution:
即使有点晚,最好的解决方案应该是 Ray 的答案,但是您必须将默认字段分隔符环境变量 IFS 覆盖为换行符,以便将完整行作为数组字段。填充数组后,您应该将 IFS 切换回原始值。我将扩展光线解决方案:
# keep original IFS Setting
IFS_BAK=${IFS}
# note the line break between the two quotes, do not add any whitespace,
# just press enter and close the quotes (escape sequence "\n" for newline won't do)
IFS="
"
X=( $(find /xyz/abc/music/ | grep def) )
echo ${X[1]}
echo ${X[2]}
echo ${X[3]}
echo ${X[4]}
# set IFS back to normal..
IFS=${IFS_BAK}
Hope this helps
希望这可以帮助
回答by afsal thaj
this will work
这会起作用
array_name=(`find directorypath | grep "string" | awk -F "\n" '{print }'`)
echo $array_name
回答by leon
Do you mean to get the first line of the output?
你的意思是得到输出的第一行?
find /xyz/abc/music/ |grep def|head 1