Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search and replace a string in the lines added in the last X commits?

Tags:

git

replace

sed

I made 5 commits in which I referenced some variable FooObj. Then I realised that FooObj was the wrong choice and created BarObj. Now I want to make a commit that replaces all instances of string FooObj with BarObj only in the lines added in those 5 commits.

I can't do a search & replace over the whole codebase because FooObj is still used correctly in many places; it must be localised to those 5 commits.

I can do this replacing manually but is there an automated way?

like image 591
DBedrenko Avatar asked Feb 24 '15 14:02

DBedrenko


People also ask

How do I replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.

How does Git calculate diff?

The git diff command displays the differences between files in two commits or between a commit and your current repository. You can see what text has been added to, removed from, and changed in a file. By default, the git diff command displays any uncommitted changes to your repository.


1 Answers

You can get the list of files in the last 5 commits via git diff --name-only HEAD~5. Then you can pipe that into a sed command to replace your variable name with xargs.

So the whole command would end up looking something this:

git diff --name-only HEAD~5 | xargs sed -i 's/FooObj/BarObj/g'

This should result in the correct files being updated for you. Verify that the changes are correct and you can commit them as usual.

EDIT

Since you only want the lines changed in your commits the method won't be quite as automated but you can create a patch fix the lines and apply it which should result in the changes that you want.

http://www.thegeekstuff.com/2014/03/git-patch-create-and-apply/

You would create a patch file and apply it via:

git diff HEAD~5 HEAD >> BarObjPatch.diff
//Edit the patch file to correct the changes.
//As noted in the comments, be careful as this will modify context lines
sed -i 's/FooObj/BarObj/g' BarObjPatch.diff //Can also edit file manually
git apply BarObjPatch.diff

This should result in the changes that you want.

like image 157
Schleis Avatar answered Oct 13 '22 09:10

Schleis