我经常使用它,我尝试实现的改进是避免回显在 grep 中不匹配的文件名。更好的方法来做到这一点?
for file in `find . -name "*.py"`; do echo $file; grep something $file; done
Run Code Online (Sandbox Code Playgroud)
Sté*_*las 25
find . -name '*.py' -exec grep something {} \; -print
Run Code Online (Sandbox Code Playgroud)
将在匹配行后打印文件名。
find . -name '*.py' -exec grep something /dev/null {} +
Run Code Online (Sandbox Code Playgroud)
将在每个匹配行的前面打印文件名(我们添加/dev/null只有一个匹配文件的情况,因为grep如果只传递一个文件进行查找,则不会打印文件名。GNU 实现grep有一个-H选项)作为备选)。
find . -name '*.py' -exec grep -l something {} +
Run Code Online (Sandbox Code Playgroud)
将只打印至少有一个匹配行的文件的文件名。
要在匹配行之前打印文件名,您可以改用 awk:
find . -name '*.py' -exec awk '
FNR == 1 {filename_printed = 0}
/something/ {
if (!filename_printed) {
print FILENAME
filename_printed = 1
}
print
}' {} +
Run Code Online (Sandbox Code Playgroud)
或者grep为每个文件调用两次 - 尽管效率较低,因为它会grep为每个文件运行至少一个命令,最多运行两个命令(并读取文件的内容两次):
find . -name '*.py' -exec grep -l something {} \; \
-exec grep something {} \;
Run Code Online (Sandbox Code Playgroud)
在任何情况下,你不想遍历的输出find一样,并记得引用您的变量。
如果您想使用 shell 循环,请使用 GNU 工具:
find . -name '*.py' -exec grep -l --null something {} + |
xargs -r0 sh -c '
for file do
printf "%s\n" "$file"
grep something < "$file"
done' sh
Run Code Online (Sandbox Code Playgroud)
(也适用于 FreeBSD 和衍生产品)。
如果您使用的是 GNU grep,您可以使用它的-r或--recursive选项为您做这个简单的查找:
grep -r --include '*.py' -le "$regexp" ./ # for filenames only
grep -r --include '*.py' -He "$regexp" ./ # for filenames on each match
Run Code Online (Sandbox Code Playgroud)
仅find当您需要更高级的谓词时才需要。
小智 5
您可以告诉 grep 在输出中包含文件名。因此,如果有匹配项,它将显示在控制台上;如果文件中没有匹配项,则不会为该文件打印任何行。
find . -name "*.py" | xargs grep -n -H something
Run Code Online (Sandbox Code Playgroud)
来自man grep:
-H Always print filename headers with output lines
-n, --line-number
Each output line is preceded by its relative line number in the file, starting at line 1. The line number counter is reset for each file processed.
This option is ignored if -c, -L, -l, or -q is specified.
Run Code Online (Sandbox Code Playgroud)
如果您的文件名称中可能有空格,则必须切换管道以使用 NUL 字符作为分隔符。完整的命令现在看起来像这样:
find . -name "*.py" -print0 | xargs -0 grep -n -H something
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53920 次 |
| 最近记录: |