100 Useful Command-Line Utilities

by Oliver; 2014

81. xargs

xargs is a nice shortcut to avoid using for loops. For example, let's say we have a bunch of .txt files in a folder and they're symbolic links we want to read. The following two commands are equivalent:
$ for i in *.txt; do readlink -m $i; done
$ ls *.txt | xargs -i readlink -m {}
In xargs world, the {} represents "the bucket"—i.e., what was passed through the pipe.

Here are some more examples. Make symbolic links en masse:
$ ls /some/path/*.txt | xargs -i ln -s {}
grep a bunch of stuff en masse:
$ # search for anything in myfile.txt in anotherfile.txt
$ cat myfile.txt | xargs -i grep {} anotherfile.txt 
xargs works particularly well with find. For example, zip all the files with extension .fastq (bioinformatics) found in a directory or any of its sub-directories:
$ find my_directory -name "*.fastq" | xargs -i gzip {}
Delete all pesky .DS_store files in the cwd or any of its sub-directories:
$ find ./ -name ".DS_Store" | xargs -i rm {} 

<PREV   NEXT>