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

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

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


当前回答

在您的示例中,将find的输出输送到xargs的目的是,find的-exec选项的标准行为是对每个找到的文件执行一次命令。如果您正在使用find,并且想要它的标准行为,那么答案很简单——一开始就不要使用xargs。

其他回答

似乎我没有足够的声望对上面的Tobia的回答添加评论,所以我添加这个“答案”是为了帮助那些希望在Windows平台上以同样的方式试验xargs的人。

下面是一个windows批处理文件,它做的事情与Tobia快速编码的“show”脚本相同:

@echo off
REM
REM  cool trick of using "set" to echo without new line
REM  (from:  http://www.psteiner.com/2012/05/windows-batch-echo-without-new-line.html)
REM
if "%~1" == "" (
    exit /b
)

<nul set /p=Args:  "%~1"
shift

:start
if not "%~1" == "" (
    <nul set /p=, "%~1"
    shift
    goto start
)
echo.

在您的示例中,将find的输出输送到xargs的目的是,find的-exec选项的标准行为是对每个找到的文件执行一次命令。如果您正在使用find,并且想要它的标准行为,那么答案很简单——一开始就不要使用xargs。

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

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

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

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

用xargs (GNU findutils) 4.4.0测试

您可以分别使用——max-lines或——max-args标志限制行数或参数(如果每个参数之间有空格)。

-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. --max-lines[=max-lines], -l[max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-args is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. --max-args=max-args, -n max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit.