Sometimes you need to process files alone. But when you don't, it is faster to run a command on as many files as possible at a time, rather than once per file. Doing this saves on the time it takes to start up the command each time.
To run a command on more than one file at once, use the xargs
command, which is invoked like this:
xargs [option...] [command [initial-arguments]]
xargs
reads arguments from the standard input, delimited by
blanks (which can be protected with double or single quotes or a
backslash) or newlines. It executes the command (default is
`/bin/echo') one or more times with any initial-arguments
followed by arguments read from standard input. Blank lines on the
standard input are ignored.
Instead of blank-delimited names, it is safer to use `find -print0'
or `find -fprint0' and process the output by giving the `-0'
or `--null' option to GNU xargs
, GNU tar
, GNU
cpio
, or perl
.
You can use shell command substitution (backquotes) to process a list of arguments, like this:
grep -l sprintf `find $HOME -name '*.c' -print`
However, that method produces an error if the length of the `.c'
file names exceeds the operating system's command-line length limit.
xargs
avoids that problem by running the command as many times as
necessary without exceeding the limit:
find $HOME -name '*.c' -print | grep -l sprintf
However, if the command needs to have its standard input be a terminal
(less
, for example), you have to use the shell command
substitution method.
Go to the first, previous, next, last section, table of contents.