将grep输出存储在数组中 [英] Store grep output in an array
本文介绍了将grep输出存储在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在目录中搜索模式,并将包含该模式的文件的名称保存在数组中.
I need to search a pattern in a directory and save the names of the files which contain it in an array.
搜索模式:
grep -HR "pattern" . | cut -d: -f1
这会向我显示所有包含模式"的文件名.
This prints me all filenames that contain "pattern".
如果我尝试:
targets=$(grep -HR "pattern" . | cut -d: -f1)
length=${#targets[@]}
for ((i = 0; i != length; i++)); do
echo "target $i: '${targets[i]}'"
done
这仅打印一个包含带有所有filname的字符串的元素.
This prints only one element that contains a string with all filnames.
output: target 0: 'file0 file1 .. fileN'
但是我需要:
output: target 0: 'file0'
output: target 1: 'file1'
.....
output: target N: 'fileN'
如何在不对目标进行无聊的拆分操作的情况下获得结果?
How can I achieve the result without doing a boring split operation on targets?
推荐答案
您可以使用:
targets=($(grep -HRl "pattern" .))
请注意使用(...)
在BASH中创建数组.
Note use of (...)
for array creation in BASH.
此外,您还可以使用grep -l
在grep
的输出中仅获取文件名(如我的命令所示).
Also you can use grep -l
to get only file names in grep
's output (as shown in my command).
这篇关于将grep输出存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文