Default
https://www.thegeekstuff.com/2013/12/xargs-examples/ The xargs command (by default) expects the input from stdin, and executes /bin/echo command over the input.
$ xargs
$ Hello
$ World
Ctrl+d
Hello World
Split lines / -n
The output of the xargs command can be split into multiple lines using -n option.
$ echo a b c d e f
a b c d e f
$ echo a b c d e f | xargs -n 3
a b c
d e f
Prompt / -p
Using option -p, you can confirm the execution of the xargs command from the user.
$ echo a b c d e f | xargs -n 3 -p
echo a b c ?...y
a b c
echo d e f ?...y
d e f
Print command / -t
Print the Command Along with Output Using -t Option
$ echo abc | xargs -t
echo abc
abc
Find Command
It is one of the most important usage of xargs command. When you need to find certain type of files and perform certain actions on them (most popular being the delete action).
$ touch one.c one.h two.c two.h
$ ls
one.c one.h two.c two.h
$ find . -name "*.c" | xargs rm -fr
one.h two.h
Space in the filenams
Use the -print0 option with find command and -0 option with xargs command to delete files including those that has space
$ find . -name "*.c" -print0 | xargs -0 rm -rf
Grep command
The xargs command can be combined with grep command to filter particular files from the search results of the find command. The xargs command executes the grep command to find all the files (among the files provided by find command) that contained a string ‘one’.
$ touch one.c one.h two.c two.h
$ find . -name "*.c" | xargs grep "one"
#nothing
$ find . -name "*.c" | grep "one"
./one.c
$ echo "one" > one.c
$ find . -name "*.c" | xargs grep "one"
./one.c
Find and move files
https://unix.stackexchange.com/questions/90886/how-can-i-find-files-and-then-use-xargs-to-move-them
$ touch one.c two.c one.h two.h
$ ls
one.c two.c one.h two.h
$ mkdir test
$ls
one.c two.c one.h two.h test
$ find . -name "*.c" | xargs mv -t test/
$ ls
one.h two.h test
The -t key puts the destination folder first, freeing up mv command to have all last arguments as just the files to be moved.
Last update: 155 days ago