script to do a global search and replace in a git repository

13 Dec 2011

There are many instances where I had to replace some variable name in all my files. I use a small script to do this, Hope it helps you too.

 1 #!/bin/bash
 2 #~/.scripts/git-sub
 3 #Author: Khaja Minhajuddin <minhajuddin@cosmicvent.com>
 4 #script which does a global search and replace in the git repository
 5 #it takes two arguments
 6 #e.g. git sub OLD NEW
 7 
 8 old=$1
 9 new=$2
10 
11 for file in $(git grep $old | cut -d':'  -f 1 | uniq)
12 do
13   echo "replacing '$old' with '$new' in '$file'"
14   sed -i -e "s/$old/$new/g" $file
15 done

Just remember to add it to a directory which is in the $PATH. I have it in my ~/.scripts directory which is included in the $PATH. Name it git-sub and give it executable permissions using chmod +x ~/.scripts/git-sub. Now, you can just call git sub old_var new_var on terminal and it will do a global search and replace of all the files in the repository.