Linux搜索文件与给定的名称递归包含字符串



从Linux shell中,假设我在目录/dir中,我想在所有子文件夹中递归地找到名称中包含字符串name_string和内部包含字符串content_string的所有文件。name_string可能位于文件名的开头、中心或末尾。我怎么能这么做呢?

我试图起诉grep为:

grep -r content_string /dir/*name_string*

但是到目前为止我还没有那么幸运。

谢谢!

find命令的-exec grep可以解决您的问题,如下例所示:

find /dir -name "*name_string*" -exec grep "content_string" {} /dev/null ;

但是,不仅会显示文件名,还会显示包含content_string的行。如果你只想要字符串的名字:

find /dir -name "*name_string*" -exec grep -l "content_string" {} ;

很明显,您可以使用-exec与其他命令(head,tailchmod…)

您也可以将findxargs一起使用

find /dir -name "*name_string*"|xargs -0 -I '{}' grep "content_string" '{}'

对于xargs -0,grep只执行一次,它的参数是所有找到的具有指定模式的文件:

grep file1 file2 file3 filen
#it will much faster because there is no overhead in fork and exec like this:
grep file1
grep file2
grep file3
..

最新更新