如何使用 -EXEC 对 FIND 的结果进行 grep 并仍输出到文件?

bak*_*ytn 90 find

最好用例子来解释。

我可以:

find . -name "*.py" -type f > output.txt
Run Code Online (Sandbox Code Playgroud)

但是如何将输出存储到同一个文件中:

find . -name "*.py" -type f -exec grep "something" {} \
Run Code Online (Sandbox Code Playgroud)

我不能只是做

find . -name "*.py" -type f -exec grep "something" {} \ > output.txt
Run Code Online (Sandbox Code Playgroud)

小智 141

如果我理解正确,这就是你想要做的:

find . -name '*.py' -print0 | xargs -0 grep 'something' > output.txt
Run Code Online (Sandbox Code Playgroud)

查找所有扩展名为 的文件.pygrep仅查找包含something行并将行保存在output.txt. 如果output.txt文件存在,它将被截断,否则将被创建。

使用-exec

find . -name '*.py' -exec grep 'something' {} \; > output.txt
Run Code Online (Sandbox Code Playgroud)

我在这里合并了 Chris Downs 评论:上面的命令将导致grep执行次数与find找到通过给定测试的路径名一样多(仅-name上面的单个测试)。但是,如果您\;用 a替换+,grep则使用多个路径名调用find(最多达到某个限制)。

有关该主题的更多信息,请参阅问题Using分号 (;) vs plus (+) with exec in find

  • 使用 `+` 而不是 `\;`,它将显着缩短执行时间(因为它会在执行之前连接参数,直到 `ARG_MAX`)。 (21认同)
  • 如果要在输出中包含文件的文件名,请使用`grep -H`。 (7认同)

Gil*_*il' 21

如果你想所有的匹配线之间保存中的所有文件output.txt,你的最后一个命令不工作,只是你缺少所需;的命令结束。

find . -name "*.py" -type f -exec grep "something" {} \; > output.txt
Run Code Online (Sandbox Code Playgroud)

如果您希望每次运行都grep将输出生成到不同的文件,请运行 shell 来计算输出文件名并执行重定向。

find . -name "*.py" -type f -exec sh -c 'grep "something" <"$0" >"$0.txt"' {} \;
Run Code Online (Sandbox Code Playgroud)


小智 13

作为记录,您可以使用grephas--include--excludearguments 来过滤它搜索的文件:

grep -r --include="*.py" "something" > output.txt
Run Code Online (Sandbox Code Playgroud)

  • 至少 GNU `grep` 可以。 (2认同)