Clayton Stanley Clayton Stanley - 2 months ago 6
Git Question

Is there a 'git sed' or equivalent?

Let's say I want to rename a method in source code contained in a git repository. I could do this by hand, but the method name might be in multiple places (e.g., unit test, documentation, actual method). To check where the method is used, I use 'git grep'. I get 'git grep' to show only lines that I want to change, and then I don't have a workflow to automatically change those lines.

I'm looking for an automated way (hopefully using git tools) to do this last step. I was hoping there was some sort of 'git sed' or equivalent, but I can't find any.

The interface I'm thinking would be nice: git sed 's/old-method-name/new-method-name/g'

Answer

You could do a

for i in $(git grep --full-name -l old_method_name)
do
 perl -p -i -e 's/old_method_name/new_method_name/g' $i
done

stick that in a file somewhere and then alias it as git sed in your config.

Update: The comment by tchrist below is a much better solution since it prevents perl from spawning repeatedly.

Comments