2017-03-07 108 views
5

我使用以下命令在目录结构中递归查找字符串。在Unix中使用find命令时忽略“是目录”结果

find . -exec grep -l samplestring {} \; 

但是,当我一个大目录结构中运行命令,将有

grep: ./xxxx/xxxxx_yy/eee: Is a directory 
grep: ./xxxx/xxxxx_yy/eee/local: Is a directory 
grep: ./xxxx/xxxxx_yy/eee/lib: Is a directory 

一个长长的清单我想省略上述结果。只需显示字符串即可获取文件名。有人可以帮忙吗?

回答

3

每当你说find .,该实用程序将当前目录结构中返回的所有元素:文件,目录,链接...

如果你只是想找到的文件,只是这么说!

find . -type f -exec grep -l samplestring {} \; 
#  ^^^^^^^ 

但是,您可能希望找到包含字符串的所有文件说:

grep -lR "samplestring" 
+2

'find -type f'和'grep -r'或'grep -R'是不错的选择......只是为了完成答案,或许加上'-d skip'专门照顾'是一个目录'问题......至少在使用递归搜索的shell选项的情况下,例如'grep -d skip -l'samplestring'**/@(* .txt | * .log)' – Sundeep

+1

@Sundeep不错!我不知道'-d'标志。 – fedorqui

3

grep -sgrep --no-messages

这是值得一读的可移植性the GNU grep documentation指出,如果你希望使用不过这个代码有多个地方:

-s --no-messages Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, 7th Edition Unix grep did not conform to POSIX, because it lacked -q and its -s option behaved like GNU grep’s -q option.1 USG-style grep also lacked -q but its -s option behaved like GNU grep’s. Portable shell scripts should avoid both -q and -s and should redirect standard and error output to /dev/null instead. (-s is specified by POSIX.)

+0

我不认为这是有用的隐藏错误,当你可以避免它们。看到我的答案 – fedorqui