Git grep replace string


Find all occurrences of $MATCH and replace with $REPLACE (inspired by this post):

git grep -l "$MATCH" | xargs sed -i "" -e "s/$MATCH/$REPLACE/g"

Find all occurrences of $MATCH but exclude $EXCLUDE and replace with $REPLACE:

git grep -l -e "$MATCH" --and --not -e "$EXCLUDE" | xargs sed -i "" -e "/$EXCLUDE/! s/$MATCH/$REPLACE/g"

Example

Here’s an example of how to replace foo with bar in your repository:

MATCH="foo"
REPLACE="bar"
git grep -l "$MATCH" | xargs sed -i "" -e "s/$MATCH/$REPLACE/g"

Here’s an example of how to replace foo with bar (but not foobar) in your repository:

MATCH="foo"
EXCLUDE="foobar"
REPLACE="bar"
git grep -l -e "$MATCH" --and --not -e "$EXCLUDE" | xargs sed -i "" -e "/$EXCLUDE/! s/$MATCH/$REPLACE/g"

Explanation

git grep prints lines matching a pattern in the repository:

git grep "$MATCH"

git grep -l prints file paths matching a pattern in the repository:

git grep -l "$MATCH"

--and --not -e is used to exclude a pattern:

git grep -l -e "$MATCH" --and --not -e "$EXCLUDE"

The file paths are piped to xargs, which converts the paths into arguments for the sed command:

$FILE_PATHS | xargs sed

sed then does a global string replacement in place of the file:

sed -i "" -e "s/$MATCH/$REPLACE/g"

To learn more about sed, see “Replace text with sed”.

Finally, /$EXCLUDE/! in the command helps exclude a pattern from the match:

sed -i "" -e "/$EXCLUDE/! s/$MATCH/$REPLACE/g"


Please support this site and join our Discord!