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!
Written by Julio A. Mistral
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shell scripting
Authors
juliomistral
25.98K
jseb
1.003K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#