xargs - macOS
Overview
xargs is a powerful command-line utility that constructs and executes command-lines from standard input. It’s commonly used to split up large lists of arguments into smaller batches, making it easier to process them with other commands.
Syntax
xargs [-0] [-a file] [-d delim] [-e eofstr] [-i replace-str] [-l max-args] [-n max-args] [-p] [-s max-chars] [--null] [--verbose] [--replace] [--eof-str] [--exit] [--delimiter] [--max-args] [--max-chars] [--interactive] [--line-buffered] [--pending] [--show-limits] [--arg-file] [command [initial-arguments]]]
Options/Flags
-0
,--null
: Use null characters as delimiters instead of whitespace.-a file
,--arg-file
: Read arguments from the specified file.-d delim
,--delimiter
: Specify a custom delimiter. Default is whitespace.-e eofstr
,--eof-str
: Appendeofstr
to the end of the command line.-i replace-str
,--replace
: Replacereplace-str
in the command line with each argument.-l max-args
,--max-args
: Limit the number of arguments per command line.-n max-args
,--max-chars
: Limit the number of characters per command line.-p
,--interactive
: Prompt for confirmation before executing commands.-s max-chars
,--max-chars
: Limit the total character length of the command line.
Examples
Example 1: Execute rm
with a list of files
find . -name "*.txt" | xargs rm
Example 2: Use xargs
with the -n
option to process 5 files at a time
find . -name "*.txt" | xargs -n 5 rm
Example 3: Replace {}
with the first argument in the command line
echo "Delete file: {}" | xargs -i /bin/rm {}
Common Issues
- Error: Argument list too long: Use the
-n
or-s
options to limit the number of arguments or characters per command line. - Error: No command specified: Provide a command after the options.
Integration
- Chaining with
find
: Usefind
to generate a list of arguments (e.g., file paths), then pipe the output toxargs
to execute commands on them. - Combining with
parallel
: Usexargs
to create multiple commands from a single list of arguments, then execute them in parallel withparallel
.
Related Commands
find
: Generates a list of files or directories.awk
: A text processing tool.parallel
: Executes multiple commands in parallel.