bash - grep 后 grep : No such file or directory

标签 bash grep

要创建一个文件名首先包含空格的测试文件:

vim  "/tmp/it is a test.txt"
bash  escape

使用 grep 搜索:

grep    -lr   'bash'  /tmp
/tmp/it is a test.txt

我想在 grep 之后执行 grep 命令:

grep    -lr   'bash'  /tmp  | xargs grep  escape
grep: /tmp/it: No such file or directory
grep: is: No such file or directory
grep: a: No such file or directory
grep: test.txt: No such file or directory

所以我在 xargs 中添加 -0:

grep    -lr   'bash'  /tmp | xargs -0 grep  escape
grep: /tmp/it is a test.txt
: No such file or directory

我找到原因了:

grep    -lr   'bash'  /tmp | xargs -0 
grep: /tmp/it is a test.txt
#a blank line at the bottom

xargs -0 添加一个空行!
如何抑制输出 : No such file or directory

最佳答案

正如您可能已经猜到的,您尝试的第一个版本

grep -lr 'bash' /tmp | xargs grep escape

失败,因为xargs假设从标准输入获取的参数由以下分隔:

space, tab, newline and end-of-file.

通过添加 -0 CLI 选项,您已经步入正轨:

grep -lr 'bash' /tmp | xargs -0 grep escape

但要使其完全正常工作,您还需要确保 xargs 的输入确实由 NUL 字符分隔。

因此以下命令依赖 tr :

grep -lr 'bash' /tmp | tr '\n' '\0' | xargs -0 grep escape

或者,更好的解决方案是直接使用 grep--null CLI 选项:

grep -lr --null 'bash' /tmp | xargs -0 grep escape

或更简洁地说:

grep -lrZ 'bash' /tmp | xargs -0 grep escape

顺便说一句

I find the reason:
xargs -0 add a blank line!

进一步解释一下:

xargs -0 单独相当于 xargs -0 echo,并且由于 -0xargs 看到由 grep 打印的最终 换行符(包含在内,因为您没有使用 --null CLI 选项)作为字符的一部分文件名...然后由 echo 打印。

关于bash - grep 后 grep : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70144684/

相关文章:

bash - 通过 ssh 调用交互式 bash 脚本

linux - Grep 命令需要解释

regex - Grep 中间的通配符

linux - 仅打印一次包含字符串的行

bash - uniq - 比较行时跳过最后 N 个字符/字段

bash - 如何转义变量中的特殊字符以在 bash 中提供命令行参数

regex - 如何在 perl 替换中转义 REPLACEMENT?

eclipse - 从命令行刷新eclipse

Unix 命令在另一个 file2 中搜索 file1 id 并将结果写入 file3

parsing - 从 HTML 文件中获取 jpg 图像