2016-12-16 97 views
0

我想在Linux的特定目录中查找文件,而无需查看其子目录,其中包含文本中的特定字符串。从this答案,我想这消除递归的r后:使用Linux获取包含特定文本的文件

grep -nw '/path/to/somewhere/' -e "pattern" 

但它不能正常工作。我也试图与跳绳目录选择启用:

grep -rnw -d skip '/path/to/somewhere/' -e "pattern" 

我试图排除是从当前目录不同的任何目录,但也没办法:

grep -rnw -exclude-dir '[^.]' '../../path/to/somewhere/' -e "pattern" 
+0

'发现。-type f -name'* pattern *'' –

+0

这些将会查看'pattern'的路径中的所有文件我想这不是你想要做的。 'find'或'ls ... | grep'会有帮助 – nu11p01n73R

+0

如果你还想用grep试试'grep/path/to/somewhere/* -d skip -le“pattern”' – bansi

回答

2

可能是混淆的问题,我希望现在清楚,模式应该匹配内容而不是文件名!

你的问题并不清楚,并在原来的答案我已经展示了如何找到文件名匹配的模式。如果您只想搜索内容匹配模式的文件,就如同

grep 'pattern' directory/* 

(使用shell匹配)。

,您仍然可以使用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' {} + 
+1

是的,'grep'pattern'*'更多远远不够。 – fedorqui

+0

虽然它显示子目录的错误,但它的可接受的答案,thx男子! – 54l3d

1

使用find

find '/path/to/somewhere' -maxdepth 1 -type f -exec grep -H 'pattern' {} \; 
0

如果图案必须是正则表达式:

ls -A /path/to/dir | grep -E PATTERN 
相关问题