Skip to content

Instantly share code, notes, and snippets.

@walterhiggins
Last active March 28, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterhiggins/7036f64c28b92c1c344333ae60df9bc1 to your computer and use it in GitHub Desktop.
Save walterhiggins/7036f64c28b92c1c344333ae60df9bc1 to your computer and use it in GitHub Desktop.

I've been using xargs for years without truly understanding what it did. I assumed it repeated the same command on each file but instead it runs the command passing all the files as arguments.

To run a command on multiple files - 1 file at a time - do this:

for file in $DIRECTORY/*; do ${YOUR_COMMAND_HERE} ${file}; done

For example: to revert local changes in a git-managed directory:

for file in ./*; do git checkout -- ${file}; done

To replace smart-quotes with ' and " chars:

for file in ./blog/posts/*.md; do 
sed "
s/’/'/g
s/‘/'/g
s/–/-/g
s/—/-/g
s/ / /g
s/“/\"/g
s/”/\"/g
" < ${file} > ${file}.temp
mv ${file}.temp ${file}
done

Update

The above examples don't work on a tree - only the files in the current directory. Another option is:

find . -type f | while read line; do grep -H "SOMETHING" "${line}"; done

Good to know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment