grep 中的 -z 和 -Z

-z and -Z in grep

我在参数 -z-Z 上粘贴了 grep 手册。

   -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. 中是什么意思?

Why -z add 0a instead of 00?What does output mean in Treat 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. 数据将被解释为具有空终止行而不是换行终止行。

  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 生效时,它会在每一行之前加上文件名和一个空字符。