Find and replace a pattern in a codebase with capture groups
Sure, you can do this with your editor, but did you know you can quickly and easily replace a pattern of text from the command line?
Check out this excellent tip from Will Keleher:
git grep -l pattern | xargs gsed -ri 's|pat(tern)|\1s are birds|g'
git grep -l
: make sure we're only looking for files in our codebase (ag -l
is another good option)
xargs
: allow running this with gsed -i
gsed -i
: edit files (default mac sed
is bad, so gnu-sed is essential)
gsed -r
: use regular expression for the pattern to allow capture groups
s|
: the first character after the s
is used as the delimiter. /
is pretty consistently annoying because it's used in file paths & urls.
gsed '...'
: the single quotes are important to avoid escapes
's|pat(tern)|\1s are birds|g'
: being able to easily use capture groups in a find and replace is amazing
|g
: replace this multiple times in a line
Source: Will Keleher's article on Bash Patterns