从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
,tail
、chmod
…)
您也可以将find
与xargs
一起使用
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
..