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

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

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


当前回答

在当前或子文件夹的每个build.xml上执行ant任务clean-all。

find . -name 'build.xml' -exec ant -f {} clean-all \;

其他回答

@Draemon的答案似乎是正确的“-0”,即使在文件中有空格。

我正在尝试xargs命令,我发现“-0”与“-L”完美地工作。即使空格也会被处理(如果输入以空结尾)。举例如下:

#touch "file with space"
#touch "file1"
#touch "file2"

下面的代码将拆分null值,并对列表中的每个参数执行命令:

 #find . -name 'file*' -print0 | xargs -0 -L1
./file with space
./file1
./file2

因此-L1将对每个以null结尾的字符执行参数,如果使用"-0"。要看区别,试试:

 #find . -name 'file*' -print0 | xargs -0 | xargs -L1
 ./file with space ./file1 ./file2

即使这样也会执行一次:

 #find . -name 'file*' -print0  | xargs -0  | xargs -0 -L1
./file with space ./file1 ./file2

该命令将执行一次,因为“-L”现在不会在空字节上分裂。你需要同时提供“-0”和“-L”才能工作。

如果你想对来自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

这两种方法也可以工作,并将适用于其他没有使用find!

xargs -I '{}' rm '{}'
xargs -i rm '{}'

示例用例:

find . -name "*.pyc" | xargs -i rm '{}'

将删除此目录下的所有pyc文件,即使pyc文件包含空格。

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

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.
find path -type f | xargs -L1 command 

这就是你所需要的。