你不能在 bash 中使用 NUL 作为参数
您不能使用$'\0' 作为参数,将其存储为变量或使用命令替换$(printf '\0'),因为bash(以及大多数shell?)使用以null 结尾的C 字符串。 NUL 之前的前导字符串被解释为字符串,而尾随字符串被丢弃。
您只能使用管道输入 - printf '\0' | cat -v 或让生成的程序使用文件进行输入。
使用另一种输入方式
大多数使用行字符串NUL 字符串(xargs、cut、...)输入的程序通常都有一个-z 标志。这主要用于处理路径,因为字符可能包含除NUL 之外的任何字符。
像find 和git ls-files 这样的程序支持输出这种格式,通常以-print0 或-0 标志的形式。
sed、tr、bash 等程序。人。使用 \0、\x0、\x00 等特殊转义字符生成 NUL 字节。
按摩输入
OP原本似乎想知道如何use cut with a NUL delimiter。问题通常是使用\n 分隔某些内容,其中\n 是值的有效部分,而不是行分隔符(通常在路径中)。
假设您将文件分组,每个文件由NUL 字符分隔,组由\n 分隔。
# Temporary mock output with NUL columns and newline rows
printf 'foo\0bar\nbar\0\nFOO\0BAR\0\n' > /tmp/$$.output
一种变通方法是通过组合sed、awk 或tr 来发挥创意,将输出调整为适合我们输入/命令的内容。
我们的.sed
#!/usr/bin/sed -nf
# beginning
:x
# match \0\n
/\x0$/ {
# Change \0\n to \n
s|\x0$|\n|g
# print
p
# delete
d
}
# match \n with no leading \0
/[^\x0]$/ {
# change \0 to \1
s|\x0|\x1|g
# read next line
N
# branch to beginning
bx
}
在这种情况下,我们映射:
-
\0\n => \n
-
\0 后面没有\n => \1
虽然文件名中的字符是有效字符,但不太可能造成问题。
# Change NUL to another unlikely to be used control character
sed -f our.sed /tmp/$$.output |\
cut -d $'\x1' -f 2
输出
bar
BAR