-z and -Z in grep

  • 本文关键字:grep in and bash grep
  • 更新时间 :
  • 英文 :


我将grep手册粘贴到参数-z-Z上。

-z, --null-data
Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.  Like the -Z  or  --null
option, this option can be used with commands like sort -z to process arbitrary file names.
-Z, --null
Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name.  For example, grep -lZ outputs a zero byte  after
each  file  name instead of the usual newline.  This option makes the output unambiguous, even in the presence of file names containing unusual characters
like newlines.  This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even  those  that
contain newline characters.

创建测试文件:

vim  "/tmp/target/it is a test.txt"
test

对于-Z,它在文件末尾输出一个零字节的00

grep -rlZ  'test' /tmp/target |xxd
00000000: 2f74 6d70 2f74 6172 6765 742f 6974 2069  /tmp/target/it i
00000010: 7320 6120 7465 7374 2e74 7874 00         s a test.txt.

对于-z,它是Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.

grep -rlz  'test' /tmp/target |xxd
00000000: 2f74 6d70 2f74 6172 6765 742f 6974 2069  /tmp/target/it i
00000010: 7320 6120 7465 7374 2e74 7874 0a         s a test.txt.

为什么-z添加0a而不是00outputTreat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.中是什么意思?

为什么-z添加0a而不是00outputTreat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.中是什么意思?

-z选项是关于grep与给定模式匹配的数据。它有两个效果:

  1. 数据将被解释为具有以null结尾的行,而不是以换行符结尾的行。

  2. grep将输入数据回显到其输出时(通常是与模式匹配的行,但如果-v有效,则是与模式不匹配的行(,则它用空字符终止该行,从而保留输入的特性。这就是";输出";指-z选项的文档中。

这两个都与您的特定数据和grep -rlz命令无关。

首先,文件/tmp/target/it is a test.txt的内容只是test——看不到空字符。因此,grep将文件的整个内容视为一行,尽管这与-z无效时也没有换行没有什么不同。

其次,-l选项有效,因此grep不打印任何匹配的行(使用空终止符(,而是打印文件名。它会附加一个换行符,因为这是它的默认值,并且您没有覆盖它——文件名打印是-Z选项的功能,而不是-z选项。

还要注意,即使-l不起作用,-Z在文件名打印上也是有效的。当-r生效或在grep命令行上给定多个文件名时,grep通常会在其打印的每一行输入数据(即每一行输出数据(前面加上相应的文件名和冒号。当-Z生效时,它会在每行前面加上文件名和一个空字符。

最新更新