xargs grep 忽略不满足查询的文件
关于使用 xargs 进行 grep 的快速问题。当我这样做时,我将显示一堆不存在的文件的结果,其中散布着成功匹配搜索条件的文件,例如:
find . | xargs grep 'Cache'
grep: PT: No such file or directory
grep: Sans: No such file or directory
grep: Free: No such file or directory
grep: Font: No such file or directory
grep: License.txt: No such file or directory
是否有一个可以传递的仅显示命中的参数?
谢谢。
Quick question regarding doing a grep with xargs. When I do it, I will be displayed with a bunch of results from files that dont exist interspersed with files that do successfully match the search criteria, such as:
find . | xargs grep 'Cache'
grep: PT: No such file or directory
grep: Sans: No such file or directory
grep: Free: No such file or directory
grep: Font: No such file or directory
grep: License.txt: No such file or directory
Is there an arg that can be passed that will only display hits?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文件名包含空格,因此您需要告诉
find
输出由 NUL 字节而不是换行符分隔的结果 - 请尝试以下操作:将-0
转换为xargs
表示将 STDIN 的数据解释为由 NUL 字节分隔。 (
Cache
周围的单引号在这里是不必要的。)类 Unix 系统上的许多工具类似地都可以选择生成或使用
由 NUL 字节分隔的数据,因为
0x00
和0x2F
(正斜杠)是文件或目录中唯一不允许的两个字节
名称 - 这是安全处理带空格的文件名的常见方法
或换行符。
最后一点,为了非常挑剔,您可能需要将其更改为:
... 这样您就可以确定
grep
总是有多个参数,并且您会得到一致的输出以文件名为前缀。The filenames contain spaces, so you need to tell
find
to output the results separated by NUL bytes rather than newlines - try the following instead:The
-0
toxargs
says to interpret the data from STDIN asbeing separated by NUL bytes. (The single quotes around
Cache
are unnecessary here.)Many tools on Unix-like systems similarly have an option to produce or consume
data separated by NUL bytes, since
0x00
and0x2F
(forward slash)are the only two bytes that aren't allowed in file or directory
names - it's a common way of dealing safely with filenames with spaces
or newlines.
As a final note, to be very picky you might want to change that to:
... so that you're sure that there will always be more than one parameter to
grep
and you get output that's consistently prefixed with the filename.如果您有 GNU
grep
,只需将其设为递归即可If you have GNU
grep
, just make it recursive当将 find 与 xargs 一起使用时,您应该始终使用 -print0 因为 http://en.wikipedia 的分隔符问题.org/wiki/Xargs#The_separator_problem 。但是,如果您有一个文件列表,每个文件都位于一行,您可能需要看一下 GNU Parallel:
观看介绍视频以了解更多信息:http://www.youtube.com/watch?v=OpaiGYxkSuQ
When using find with xargs you should always use -print0 because The separator problem of http://en.wikipedia.org/wiki/Xargs#The_separator_problem . However, if you have a list of files that are each on a line you may want to take a look at GNU Parallel:
Watch the intro video to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ