要创建一个文件名首先包含空格的测试文件:
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
,并且由于 -0
,xargs
看到由 grep
打印的最终 换行符(包含在内,因为您没有使用 --null
CLI 选项)作为字符的一部分文件名...然后由 echo
打印。
关于bash - grep 后 grep : No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70144684/