将grep输出存储在数组中[重复]

时间:2022-01-20 14:03:15

This question already has an answer here:

这个问题在这里已有答案:

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".

这将打印出包含“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.

这只打印一个包含所有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?

如果不对目标执行无聊的拆分操作,我怎样才能实现结果?

1 个解决方案

#1


41  

You can use:

您可以使用:

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

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

注意在BASH中使用(...)进行数组创建。

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

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

#1


41  

You can use:

您可以使用:

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

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

注意在BASH中使用(...)进行数组创建。

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

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