Search & replace one-liner w/ ag, xargs & perl/sed
I wrote a search-replace script to print back my changes and ask for confirmation. This isn't that.
This is the short, aggressive and simple version: me, trying to fit project-wide search & replace into a one-liner for the command line, using ag, xargs and perl (or sed).
Paste this into a shell script (e.g. replace.sh) or put it into a shell function:
ag -l "$1" | xargs perl -pi.bak -e "s/$1/$2/g"
or, if you prefer sed:
ag -l "$1" | xargs sed -ri.bak -e "s/$1/$2/g"
Works with perl-style backreferences too:
replace.sh '(foo)' '$1-bar' # foo => foo-bar
or if you use sed:
replace.sh '(foo)' '\\1-bar' # foo => foo-bar
Notes:
- Saves backup of changed files to
*.bak
- Will choke if the first or second argument has a forward slash in it (any suggestions?)
Written by Henrik Lissner
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Perl
Authors

janosgyerik
25.21K

Jean-Remy Duboc
12.28K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#