xargs by examples Linux 30.05.2014

The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments. (man)

In short, xargs takes a string and sends the string as arguments to another command. By default, xargs expects the input from stdin, and executes echo command over the input.

Command Description
ls *.txt | xargs wc -l count lines in files
ls *.txt | xargs -t wc -l showing command to be executed
echo {0..9} | xargs -n 2 the -n flag to xargs specifies how many arguments at a time to supply to the given command
echo "1,2,3,4,5" | xargs -d, echo use custome delimeter
echo "1,2,3,4,5" | xargs -d, -L 1 echo show output in sepreate line
time echo {1..10} | xargs -n 1 -P 4 sleep the -P flag allows xargs to invoke the specified command multiple times in parallel
find . -name '*.txt' -not -name "all.txt" | xargs cat > all.txt concatenate txt files
xargs -a urls.txt -L 1 echo read from file instead of stdin
cat urls.txt | xargs -I DOMAIN nslookup DOMAIN 8.8.8.8 insert argument in specific place
echo {1..6} | xargs -n2 -p prompt user before execution with -p option
find . -name "*.pyc" | xargs rm -rf delete all *.pyc files
find . -name "*.pyc" | xargs -0 rm -rf delete all *.pyc files that has white-space in the filename
find . -name "*.py" | xargs grep 'import antigravity' combine find with grep command
find . -name '*.txt' | xargs zip -9 txt.zip zip all *.txt files
cat url.txt | xargs wget –c download files from urls.txt
cat files.txt | xargs -I {} sh -c "test -e {} && echo {}" check list of files in files.txt for existence
echo "/dir1/ /dir2/ /dir3/" | xargs -n 1 cp -v foo.txt copy one file named foo.txt to multiple directories called /dir1/, /dir2/, and /dir3/