find. -name *.png -type f -print | xargs tar -cvzf images.tar.gz
cat urls.txt | xargs wget

Keep in mind that the output of the first command passed at the end of the xargs command. What if your command needs the output in the middle? Easy! Just use {} combined with the –i parameter, like below, to replace arguments in the place where the output of the first command should go:

ls /etc/*.conf | xargs -i cp {} /home/likegeeks/Desktop/out

What is the purpose of the xargs utility?

The xargs utility builds and executes command lines from standard input, and not from the command line.

What are the command line options for the xargs command?

  1. -i: allow us to put the arguments to xargs at specified places. The -i option tells xargs to replace {} with the name of each item.
  2. -t: display the constructed command before executing it.
  3. -p: allow us to selectively execute commands.
echo a b c d e f | xargs -i echo before {} after

The {} marks the place to put arguments for the -i option.

ps -ef | grep "[d]oom" | gawk '{print $2}' | xargs renice +10
file -Lz * | grep ASCII | cut -d":" -f1 | xargs ls -ltr
ls -lhd | gawk '{print $9}' | xargs -s 500 rm -rf

How can we quickly rename files in a directory?

ls | xargs -t -i mv {} {}.bak

How can we open files with xargs and vim?

Another very useful operation is when you want to open the files for editing using vim:

file * | grep ASCII | cut -d":" -f1 | xargs vim

This command opens the files one by one using vim.

Perhaps the most useful is the -p option, which makes the operation interactive:

file * | grep ASCII | cut -d":" -f1 | xargs -p vim

Here xarg asks you to confirm before running each command. If you press "y", it executes the command. You will find it immensely useful when you take some potentially damaging and irreversible operations on the file—such as removing or overwriting it.

What if the output passed to the xargs is blank?


file * | grep SSSSSS | cut -d":" -f1 | xargs -t wc -l

Here searching for "SSSSSS" produces no match; so the input to xargs is all blanks. Although this may be useful, in some cases you may want to stop xargs if there is nothing to process; if so, you can use the -r option:

file * | grep SSSSSS | cut -d":" -f1 | xargs -t -r wc -l

The command exits if there is nothing to run.

How can we limit 2 arguments per command with xargs?

Suppose you want to remove the files using the rm command, which should be the argument to the xargs command. However, rm can accept a limited number of arguments. What if your argument list exceeds that limit? The -n option to xargs limits the number of arguments in a single command line. Here is how you can limit only two arguments per command line:

file * | grep ASCII | cut -d":" -f1 | xargs -t -n2 ls -ltr

Even if five files are passed to xargs ls -ltr, only two files are passed to ls -ltr at a time.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License