我想在Linux中查找特定目录中的文件,而不查看它的子目录,该子目录中包含一个特定的字符串。从this答案中,在删除递归的r之后,我尝试了这样的方法:
grep -nw '/path/to/somewhere/' -e "pattern"但它不起作用。我也尝试过跳过optin目录:
grep -rnw -d skip '/path/to/somewhere/' -e "pattern"我试图排除任何与当前目录不同的目录,但也没有办法:
grep -rnw -exclude-dir '[^.]' '../../path/to/somewhere/' -e "pattern"发布于 2016-12-16 10:04:09
可能是这个问题令人困惑,我希望它现在清楚了,彭定康应该匹配的内容,而不是文件名!
您的问题不清楚,在最初的回答中,我已经说明了如何找到匹配模式的文件名。如果您只想搜索内容与模式匹配的文件,那么它非常简单
grep 'pattern' directory/*(使用外壳球体)。
在传递到find之前,您仍然可以使用grep过滤出文件。
find 'directory' -maxdepth 1 -mindepth 1 -type f \
-exec grep --with-filename 'pattern' {} +原始答案
Grep不是搜索文件名的适当工具,因为您需要在传递到Grep之前生成一个文件列表。即使您使用像ls | grep pattern这样的命令获得所需的结果,也必须追加另一个管道才能处理这些文件(我猜,您很可能需要以某种方式,迟早地处理它们)。
使用find代替,因为它有自己强大的模式匹配功能。
示例:
find 'directory' -maxdepth 1 -mindepth 1 -regex '.*pattern'将-iregex用于不区分大小写的-regex版本。还可以了解-name、-iname、-path和-ipath选项。
可以为使用-exec操作处理的文件运行命令(或脚本),例如:
find 'directory' -maxdepth 1 -mindepth 1 -type f \
-regex '.*pattern' -exec sed -i.bak -r 's/\btwo\b/2/g' {} +发布于 2016-12-16 10:00:29
使用find
find '/path/to/somewhere' -maxdepth 1 -type f -exec grep -H 'pattern' {} \;发布于 2016-12-16 10:04:46
如果模式必须是正则表达式:
ls -A /path/to/dir | grep -E PATTERNhttps://stackoverflow.com/questions/41181566
复制相似问题