bash 将 grep 输出存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24890764/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:56:31  来源:igfitidea点击:

Store grep output in an array

arraysbashshell

提问by Luca Davanzo

I need to search a pattern in a directory and save the names of the files which contain it in an array.

我需要在目录中搜索一个模式并将包含它的文件的名称保存在一个数组中。

Searching for pattern:

搜索模式:

grep -HR "pattern" . | cut -d: -f1

This prints me all filenames that contain "pattern".

这会向我打印所有包含“模式”的文件名。

If I try:

如果我尝试:

targets=$(grep  -HR "pattern" . | cut -d: -f1)
length=${#targets[@]}
for ((i = 0; i != length; i++)); do
   echo "target $i: '${targets[i]}'"
done

This prints only one element that contains a string with all filnames.

这仅打印一个包含所有文件名的字符串的元素。

output: target 0: 'file0 file1 .. fileN'

But I need:

但是我需要:

 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?

如何在不对目标进行无聊的拆分操作的情况下获得结果?

回答by anubhava

You can use:

您可以使用:

targets=($(grep -HRl "pattern" .))

Note use of (...)for array creation in BASH.

请注意(...)在 BASH 中使用for 数组创建。

Also you can use grep -lto get only file names in grep's output (as shown in my command).

您也可以使用grep -l仅获取grep's 输出中的文件名(如我的命令所示)。