问题描述
我经常要这样写命令(在的zsh
,如果是相关的):
I often want to write commands like this (in zsh
, if it's relevant):
find <somebasedirectory> | \
grep stringinfilenamesIwant | \
grep -v stringinfilesnamesIdont | \
xargs dosomecommand
(或里grep的更复杂的组合)
(or more complex combinations of greps)
在最近几年找到
添加了 -print0
开关,xargs的增加 -0
,它允许空值终止的文件名与名称空间处理的文件在一个优雅的方式来代替,使这个:
In recent years find
has added the -print0
switch, and xargs has added -0
, which allow handling of files with spaces in the name in an elegant way by null-terminating filenames instead, allowing for this:
find <somebasedirectory> -print0 | xargs -0 dosomecommand
然而,的grep
(至少我的版本,GNU的grep 2.10 Ubuntu的),似乎并不具有相当于消耗掉和生成空值终止线;它具有 - 空
,但这似乎只涉及到的文件,搜索,直接在使用 -l 来输出名称grep的。
However, grep
(at least the version I have, GNU grep 2.10 on Ubuntu), doesn't seem to have an equivalent to consume and generate null-terminated lines; it has --null
, but that only seems related to using -l
to output names when searching in files directly with grep.
是否有一个等效的选项或选项组合,我可以使用grep使用?另外,有一个简单而优雅的方式前preSS我简单地用命令的管道发现的 -regex
,或者Perl的?
Is there an equivalent option or combination of options I can use with grep? Alternatively, is there an easy and elegant way to express my pipe of commands simply using find's -regex
, or perhaps Perl?
推荐答案
按照 ,你可以使用输出线preFIX控制处理ASCII NULL字符方式相同的找到和的xargs 的
Use GNU Grep's --null
Flag
According to the GNU Grep documentation, you can use Output Line Prefix Control to handle ASCII NUL characters the same way as find and xargs.
-Z结果
--null结果
输出一个零字节(ASCII码NUL字符)而不是通常遵循一个文件名字符。例如,'的grep -LZ'输出每个文件名,而不是通常的换行后一个零字节。这个选项使得输出毫不含糊,即使在包含特殊字符像换行符的文件名的presence。此选项可以与命令中使用像找到-print0','perl的-0,排序-z和xargs的-0来处理任意文件名,甚至是那些包含换行符。
由于OP正确地指出,这个标志在处理输入或输出文件名的时候是最有用的。为了实际转换grep的输出使用NULL字符作为行结束,你需要使用类似工具的 SED 或 TR 的转换输出的每一行。例如:
Use tr
from GNU Coreutils
As the OP correctly points out, this flag is most useful when handling filenames on input or output. In order to actually convert grep output to use NUL characters as line endings, you'd need to use a tool like sed or tr to transform each line of output. For example:
find /etc/passwd -print0 |
xargs -0 egrep -Z 'root|www' |
tr "\n" "\0" |
xargs -0 -n1
这条管道将使用完全无效,从分开的文件名的找到的,然后再转换换行符完全无效通过的 egrep的的返回的字符串。这将通过NUL结尾的字符串下一个命令的管道,在这种情况下,仅仅是的xargs 的转动输出回到正常的字符串,但它可能是你想要的任何东西。
This pipeline will use NULs to separate filenames from find, and then convert newlines to NULs in the strings returned by egrep. This will pass NUL-terminated strings to the next command in the pipeline, which in this case is just xargs turning the output back into normal strings, but it could be anything you want.
这篇关于是否有一个grep的等效查找的-print0和xargs的的-0交换机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!