Last Updated: February 25, 2016
·
25.26K
· juliomistral

Bash xargs as a for loop

xargs</code> are is one of my favorite Bash commands eva!

Want to delete the 100 oldest *.tmp files to make some space? Try this on:

ls -tr /tmp/*.tmp | head -100 | xargs -I {} rm -f {}

The -I</code> argument tells xargs to use the option value as a token when evaluating the proceeding command. Hence, for every file name piped into xargs, xargs will generate and execute a rm command.

Another useful one is if you want to do a recursive search for a string for all files that meet some criteria. In case, I want to search for the string 'SOME_CONSTANT' in all of my test .py files:

find project/src -name '*.py' | xargs -I {} grep -Hn 'SOME_CONSTANT' {}

Enjoy!