仅显示找到的输出多个文件的grep

Only display the found output a grep of multiple files

我正在使用 grep 在文件中查找字符串。 grep 可能只会找到一个与文件名匹配的文件,可能是两个,但我只需要它在找到字符串时放入字符串,并且只需要字符串。

grep -oh 'Closing finished' /opt/cpu/hold/closing15{14..23} 

目前我得到如下输出:

grep: /opt/cpu/hold/closing1514: No such file or directory
Closing finished
Closing finished
grep: /opt/cpu/hold/closing1517: No such file or directory
grep: /opt/cpu/hold/closing1518: No such file or directory

我在 bash 脚本的一个函数中使用它,在一个 until 循环中匹配 "Closing finished" 然后继续。所以我希望输出只是 "Closing finished" 如果找到它匹配我的直到条件。

如果您想要抑制有关不存在文件的错误,只需使用 -s 选项:

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

即您的示例命令应如下所示:

grep -soh 'Closing finished' /opt/cpu/hold/closing15{14..23} 

或者,您也可以通过将错误重定向到 /dev/null 来完全抑制错误输出,如下所示:

grep -oh 'Closing finished' /opt/cpu/hold/closing15{14..23} 2>/dev/null