在Unix中使用find命令时忽略"是一个目录"

Pan*_*ndu 7 unix directory grep find

我使用以下命令在目录结构中递归地查找字符串.

find . -exec grep -l samplestring {} \;
Run Code Online (Sandbox Code Playgroud)

但是当我在一个大型目录结构中运行命令时,会有一个很长的列表

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
Run Code Online (Sandbox Code Playgroud)

我想省略上面的结果.只需显示带有字符串的文件名即可.有人可以帮忙吗?

fed*_*qui 7

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

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

find . -type f -exec grep -l samplestring {} \;
#      ^^^^^^^
Run Code Online (Sandbox Code Playgroud)

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

grep -lR "samplestring"
Run Code Online (Sandbox Code Playgroud)

  • `find -type f`和`grep -r`或`grep -R`是不错的选择...只是为了完成答案,或许补充说`-d skip`专门负责`是一个目录`问题..至少在使用shell选项进行递归搜索的情况下它是有用的,例如:grep -d skip -l'samplestring'**/@(*.txt |*.log)` (4认同)

ste*_*iva 5

grep -s 要么 grep --no-messages

这是值得一读的便携笔记的GNU grep的文件,如果你希望使用此代码的多个位置,但:

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

  • 最后!这个问题的正确答案!当您只想查看 grep '命中' 而不是所有无用的垃圾(如“是目录”)时,这就是这样做的方法。我一直在尝试使用 -v 来抑制其中包含“目录”的任何内容 - 但现在很明显为什么这不起作用:这些“是目录”是消息而不是 grep 结果本身。 (2认同)