【发布时间】:2009-09-01 13:52:25
【问题描述】:
我想在linux下找到包含特定字符串的文件。 我尝试了类似但无法成功:
找到 . -name *.txt | egrep 我的字符串
【问题讨论】:
我想在linux下找到包含特定字符串的文件。 我尝试了类似但无法成功:
找到 . -name *.txt | egrep 我的字符串
【问题讨论】:
在这里,您将文件名(find command 的输出)作为输入发送到 egrep;您实际上想对文件的内容运行 egrep。
这里有几个选择:
find . -name "*.txt" -exec egrep mystring {} \;
甚至更好
find . -name "*.txt" -print0 | xargs -0 egrep mystring
检查find command help 以检查单个参数的作用。
第一种方法将为每个文件生成一个新进程,而第二种方法将多个文件作为参数传递给 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 \{\} \;
【讨论】:
这是一个示例,它将返回所有 *.log 文件的文件路径,这些文件的行以 ERROR 开头:
find . -name "*.log" -exec egrep -l '^ERROR' {} \;
【讨论】:
您可以使用 egrep 的递归选项
egrep -R "pattern" *.log
【讨论】:
egrep -R "pattern" --include=*.log .?
如果你只想要文件名:
find . -type f -name '*.txt' -exec egrep -l pattern {} \;
如果您想要文件名和匹配项:
find . -type f -name '*.txt' -exec egrep pattern {} /dev/null \;
【讨论】: