The xargs command transforms standard input into a sequence of arguments for another command
xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input.
Blank lines on the standard input are ignored.
It's an essential tool when processing a long list of files or results generated by "find", or a loop. It allows for efficient command chaining on the command line.
generating_command | xargs command_to_execute
xargs combined with find structure :
find [location] -name "[search-term]" -type f | xargs [command]
find /home/aedesc -name "*.txt" -type f | xargs ls
This command displays all text files.
find -name "*.txt" | xargs rm
This commands finds all files with .txt extension and deletes them.
find -name "*.jpg" | xargs grep "jerba"
This command finds all files containing the word jerba and displays the result since the default behavior for xargs when there is no options is echo.
-n max-args, --max-args=max-args Maximum number of arguments per command. Allows the number of arguments transmitted to each execution of the command to be limited.
echo "1 2 3 4 5" | xargs -n 2
displays :
1 2
3 4
5
-p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Useful with destructive commands such as rm.
echo doc1 doc2 | xargs -p rm
displays :
rm doc1.txt doc2.txt?...
-0, --null : Support for special characters
Used with find -print0, this option manages file names containing special spaces or characters.
Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of- file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
find . -name "*.txt" -print0 | xargs -0 rm
-print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.
-t, --verbose Print the command line on the standard error output before executing it.
echo doc1 doc2 | xargs -t rm
displays :
rm doc1 doc2
and then execute the command.
remove files listed in a text file :
cat todo.txt | xargs rm
rename and move files
ls *.bak | xargs -I {} mv {} {}.old
More info here Man page
and here blog