如何使xargs对给定的每一行输入执行一次命令? 它的默认行为是将行分块并执行一次命令,将多行传递给每个实例。

从http://en.wikipedia.org/wiki/Xargs: 查找/path -type f -print0 | xargs -0 rm 在本例中,find为xargs的输入提供一长串文件名。然后Xargs将这个列表拆分为子列表,并对每个子列表调用rm一次。这比功能等效的版本更有效: 查找/path -type f -exec rm '{}' \;

我知道那个发现有"执行"的标志。我只是从另一种资源中引用了一个说明性的例子。


当前回答

以下仅在输入中没有空格时才有效:

xargs -L 1
xargs --max-lines=1 # synonym for the -L option

从手册页:

-L max-lines
          Use at most max-lines nonblank input lines per command line.
          Trailing blanks cause an input line to be logically continued  on
          the next input line.  Implies -x.

其他回答

以下仅在输入中没有空格时才有效:

xargs -L 1
xargs --max-lines=1 # synonym for the -L option

从手册页:

-L max-lines
          Use at most max-lines nonblank input lines per command line.
          Trailing blanks cause an input line to be logically continued  on
          the next input line.  Implies -x.

如何使xargs对给定的每一行输入执行一次命令?

- l1是一个简单的解决方案,但如果任何文件中包含空格,它就不起作用。这是find的-print0参数的一个关键函数,用'\0'字符而不是空格分隔参数。这里有一个例子:

echo "file with space.txt" | xargs -L 1 ls
ls: file: No such file or directory
ls: with: No such file or directory
ls: space.txt: No such file or directory

更好的解决方案是使用tr将换行符转换为空(\0)字符,然后使用xargs -0参数。这里有一个例子:

echo "file with space.txt" | tr '\n' '\0' | xargs -0 ls
file with space.txt

如果你需要限制调用的次数,你可以使用-n 1参数为每个输入对程序进行一次调用:

echo "file with space.txt" | tr '\n' '\0' | xargs -0 -n 1 ls

这还允许您在将换行符转换为空之前过滤find的输出。

find . -name \*.xml | grep -v /target/ | tr '\n' '\0' | xargs -0 tar -cf xml.tar

下面的命令将找到/path中的所有文件(-type f),然后使用cp将它们复制到当前文件夹。注意,使用if -I %在cp命令行中指定一个占位符,以便参数可以放在文件名之后。

find /path -type f -print0 | xargs -0 -I % cp %。

用xargs (GNU findutils) 4.4.0测试

另一种选择……

find /path -type f | while read ln; do echo "processing $ln"; done

如果你想对来自find的每一行(即结果)运行命令,那么你需要xargs做什么?

Try:

查找路径类型f -exec your-command {} \;

文本{}被文件名代替,而文本\;用于find,以便知道自定义命令在此结束。

编辑:

(在编辑你的问题,澄清你知道-exec之后)

来自man xargs:

- l max-lines 每个命令行最多使用max行非空输入行。落后于 空格使一个输入行在逻辑上被下一个输入行继续。 意味着- x。

注意,如果你使用xargs,以空格结尾的文件名会给你带来麻烦:

$ mkdir /tmp/bax; cd /tmp/bax
$ touch a\  b c\  c
$ find . -type f -print | xargs -L1 wc -l
0 ./c
0 ./c
0 total
0 ./b
wc: ./a: No such file or directory

所以如果你不关心-exec选项,你最好使用-print0和-0:

$ find . -type f -print0 | xargs -0L1 wc -l
0 ./c
0 ./c
0 ./b
0 ./a