【问题标题】:Redirect stderr to /dev/null将标准错误重定向到 /dev/null
【发布时间】:2017-11-29 05:39:21
【问题描述】:

我在 Unix 服务器上使用以下命令:

find . -type f -name "*.txt" | xargs grep -li 'needle'

由于grep -R不可用,我不得不使用这个find/xargs解决方案。每次文件无法打开时,grep 都会告诉我:

grep:无法打开“foo.txt”

我想摆脱这条消息,所以我尝试将 stderr 重定向到 /dev/null,但不知何故这不起作用。

find . -type f -name "*.txt" | xargs grep -li 'needle' 2>/dev/null

我想保留标准输出(即将结果写入控制台),并且只隐藏这些 grep 错误消息。而不是2>,我还尝试了&>,但这也没有用。我该如何解决这个问题?

【问题讨论】:

标签: linux grep


【解决方案1】:

只需将重定向移动到第一个命令,即

find ... 2>/dev/null | xargs ...

或者您可以将所有内容括在括号中:

(find ... | xargs ...) 2>/dev/null

【讨论】:

  • 谢谢,但这也不起作用 :S (find . -type f -name ".txt" | xargs grep -li 'needle') 2>/dev/null Badly放置()的。找 。 -type f -name ".txt" 2>/dev/null | xargs grep -li 'needle' 不明确的输出重定向。
【解决方案2】:

为了redirectstderr 到/dev/null 使用:

some_cmd 2>/dev/null

这里不需要xargs。 (而且你不想要它!因为它执行分词)

使用 find 的 exec 选项:

find . -type f -name "*.txt" -exec grep -li needle {} +

要抑制错误消息,请使用grep-s 选项:

来自man grep

-s, --no-messages 抑制有关不存在或不可读文件的错误消息。

给你:

find . -type f -name "*.txt" -exec grep -lis needle {} +

【讨论】:

  • 谢谢@hek2mgl,该解决方案完美运行:) 所有 grep 警告都消失了(无论我是否使用 -s 标志)。也不知道-exec 的可能性。
猜你喜欢
  • 2020-02-10
  • 2021-03-30
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多