7

我有

~/bashpractice$ ls
dir3 dir1   

我明白了

~/bashpractice$ xargs ls -l 
dir1 dir3
dir1:
total 0
-rw-r--r-- 1 abc abc 0 2011-05-23 10:19 file1
-rw-r--r-- 1 abc abc 0 2011-05-23 10:19 file2

dir3:
total 0
-rw-r--r-- 1 abc abc 0 2011-05-23 10:20 file1
-rw-r--r-- 1 abc abc 0 2011-05-23 10:20 file2

但是当我这样做时出现错误

~/bashpractice$ xargs -0 ls -l
dir1 dir3
ls: cannot access dir1 dir3
: No such file or directory

abc@us-sjc1-922l:~/bashpractice$ xargs -0 ls -l
dir1
dir3 
ls: cannot access dir1
dir3
: No such file or directory

为 xargs 指定 -0 选项时如何获取列表?

4

2 回答 2

19

例如 - 正如在man xargs

-0 更改 xargs 以期望 NUL (``\0'') 字符作为分隔符,而不是空格和换行符。预计这将与 find(1) 中的 -print0 函数一起使用。

find . -print0 | xargs -0 echo

告诉 xargs 一件事: “-0不要用空格分隔输入,而是用 NULL char”。当您需要处理名称中包含的文件和/或目录时,它通常与 find 结合使用很有用space

还有更多可以使用的命令-print0——例如grep -z

编辑 - 基于评论:

见赛斯的回答或这个:

ls -1 | perl -pe 's/\n/\0/;' > null_padded_file.bin
xargs -0 < null_padded_file.bin

但是很奇怪,不需要用为什么还要-0用呢?. 就像“为什么要删除文件,如果不存在?”。简单地说-0,如果输入是空填充的,则只需要与组合一起使用。时期。:)

于 2011-05-25T19:19:35.797 回答
3

xargs 的工作方式与您想象的不同。它接受输入并运行作为参数提供的命令以及从输入中读取的数据。例如:

find dir* -type f -print0 | xargs -0 ls -l

ls -d dir* | xargs '-d\n' ls -l

look foo | xargs echo

look foo | perl -pe 's/\n/\0/;' | xargs -0 echo

如果您怀疑输入中可能包含空格或返回值,则通常使用 -0,因此“\s”(正则表达式 \s、空格、制表符、换行符)的默认参数分隔符并不好。

于 2011-05-25T19:18:32.110 回答