在阵列的bash的grep店输出 [英] Store grep output in array bash

查看:105
本文介绍了在阵列的bash的grep店输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要寻找一个模式目录中,并保存其中包含它在数组中的文件名。

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

在搜索模式:

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

这我打印包含模式的所有文件名。

This print me all filename that contains "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 print me only one element that contains a string with all filname..

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 do a boring split operation on targets?

推荐答案

您可以使用:

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

请注意使用(...)的在BASH阵列。

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

您也可以使用的grep -l <​​/ code>在的grep 只得到文件名的输出(如图我的命令)。

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

这篇关于在阵列的bash的grep店输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆