使用 xargs 和 xargs -i 的细微差别
为什么 会找到 . -名称“*.xml”| xargs grep FOO
返回与文件名的匹配,而 find . -名称“*.xml”| xargs -i -sh -c "grep FOO {}"
不是吗?
Why does find . -name "*.xml" | xargs grep FOO
returns matchs with filenames, while find . -name "*.xml" | xargs -i -sh -c "grep FOO {}"
doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非在发布问题时出现拼写错误,否则
sh
之前不应有连字符:您在输出中没有获得文件名的原因是
grep
正在运行单个文件作为参数。要强制输出文件名,请使用-H
。此外,
xargs
的-i
在版本 4.2.9 左右已被弃用。您应该使用-I {}
。Unless it's a typo in posting your question there shouldn't be a hyphen before
sh
:The reason you don't get filenames in the output is that
grep
is being run with a single file as an argument. To force filename output use-H
.Also,
-i
forxargs
was deprecated around version 4.2.9. You should use-I {}
.正如前面的答案所述,区别在于为每个文件调用 grep ,并且如果在命令行上仅指定一个文件,则 grep 不会报告文件名,除非给出 -H (--with-filename)标志。
为什么要对每个文件调用 grep?这是因为(不管喜欢与否)对 xargs 使用 -I(或 -i)标志会强制命令为每个参数运行一次,就像使用标志“-L 1”来xargs。
从手册页:
As a previous answer said, the difference is that grep is being invoked for each file and grep doesn't report the filename if only one file is specified on the command line unless the -H (--with-filename) flag is given.
Why is grep being invoked for each file? That is because (like it or not) the use of the -I (or -i) flag to xargs forces the command to be run once for each argument, like using flag "-L 1" to xargs.
From the manual page:
您可以直接使用
,并且可以根据需要在
grep
命令中使用-H
或-n
。you can just use
and you may use
-H
or-n
ingrep
command as you need.