将 stderr 重定向到/dev/null

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

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

因为 grep -R是不可用的,我必须使用这个 找到/Xargs解决方案。每次无法打开文件时,grep都会告诉我:

不能打开“ foo.txt”

我想删除这条消息,所以我尝试将 stderr 重定向到 /dev/null,但是不知怎么地,这不起作用。

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

我想保留 stdout (即将结果写入控制台) ,并且只隐藏这些 grep 错误消息。取代 2>,我也尝试了 &>,但这也没有工作。我该怎么补救?

110467 次浏览

Just move the redirection to the first command, i.e.

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

Or you can enclose everything in parenthesis:

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

In order to redirect stderr to /dev/null use:

some_cmd 2>/dev/null

You don't need xargs here. (And you don't want it! since it performs word splitting)

Use find's exec option:

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

To suppress the error messages use the -s option of grep:

From man grep:

-s, --no-messages Suppress error messages about nonexistent or unreadable files.

which gives you:

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