grep输出到数组 [英] grep output into array
问题描述
伙计们,我该如何做
`查找/xyz/abc/music/| grep def`
`find /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]}请帮帮我
echo ${$(`find /xyz/abc/music/ |grep def`)[0]} Please help me How I can achieve this
推荐答案
如果只需要第一个元素(或者更确切地说是行),则可以使用 head
:
If you just need the first element (or rather line), you can use 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]}
但这不会将grep输出的每一行都放入数组的单独元素中.
but this will not put each line of grep output into a separate element of an array.
如果您只关心整行而不是单词,则可以使用 head
和 tail
来完成此任务,如下所示:
If you care for whole lines instead of words, you can use head
and tail
for this task, like so:
`find /xyz/abc/music/ |grep def | head -n line_number | tail -n 1`
这篇关于grep输出到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!