我想在Linux下查找包含特定字符串的文件。
我尝试了以下命令,但没有成功:
```
find . -name *.txt | egrep mystring
```
你现在正在发送文件名(即find命令
的输出)作为egrep的输入,实际上你想要运行egrep在文件内容上。
以下是几种替代方案:
find . -name "*.txt" -exec egrep mystring {} \;
甚至更好
find . -name "*.txt" -print0 | xargs -0 egrep mystring
查看find命令帮助以了解单个参数的含义。
第一种方法将为每个文件生成一个新进程,而第二种方法将把多个文件作为egrep的参数传递;-print0和-0标志用于处理可能会出现问题的文件名(例如,即使文件名包含空格,也能正确地分离文件名)。
尝试:
find . -name '*.txt' | xargs egrep mystring
*.txt
会被 shell 展开,给你列出当前目录中以 .txt
结尾的文件列表。例如,如果你有以下内容:[dsm@localhost:~]$ ls *.txt
test.txt
[dsm@localhost:~]$
你的find
命令将变成find . -name test.txt
。只需尝试以下示例:
[dsm@localhost:~]$ echo find . -name *.txt
find . -name test.txt
[dsm@localhost:~]$
egrep
无法从 STDIN
中获取文件名。为了将它们转换为参数,您需要使用 xargs
。find . -name *.txt | egrep mystring
这样做不起作用,因为egrep
将在由find . -name *.txt
生成的输出中搜索mystring
,而这些输出只是指向*.txt
文件的路径。
相反,您可以使用xargs
:
find . -name *.txt | xargs egrep mystring
你可以使用
find . -iname *.txt -exec egrep mystring \{\} \;
ERROR
开头的行的*.log
文件路径:find . -name "*.log" -exec egrep -l '^ERROR' {} \;
你可以使用egrep的递归选项
egrep -R "pattern" *.log
egrep -R "pattern" --include=*.log .
命令? - moala如果你只想要文件名:
find . -type f -name '*.txt' -exec egrep -l pattern {} \;
如果您想要文件名和匹配项:
find . -type f -name '*.txt' -exec egrep pattern {} /dev/null \;
\+
或\;
。 - drrlvn