Skip to content

Instantly share code, notes, and snippets.

@codenamev
Created March 4, 2011 12:19
Show Gist options
  • Save codenamev/854534 to your computer and use it in GitHub Desktop.
Save codenamev/854534 to your computer and use it in GitHub Desktop.
Search and replace a regex in multiple files on UNIX
egrep -lRZ "\.jpg|\.png|\.gif" . \
| xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
#egrep: find matching lines using extended regular expressions
# -l: only list matching filenames
# -R: search recursively through all given directories
# -Z: use \0 as record separator
# "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"
# .: start the search in the current directory
#xargs: execute a command with the stdin as argument
# -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.
# -l: use one line per command as parameter (NOTE -d for macs, and you must provide a number following
#sed: the stream editor
# -i: replace the input file with the output without making a backup
# -e: use the following argument as expression
# 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"
@codenamev
Copy link
Author

or with perl:

perl -i.bak -pe 's/.jpg|.png|.gif/.jpg/

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