in Shell

Find and replace in directory with grep and sed

Recently I needed to find an replace a method name in a project as part of a re-organization. So rather than just using an editor to do it for me I figured I would spend some time with a small science project on the command line.

What I was able to come up with is a combination of using grep to find all the files that had the method name in them and pipe that list to set to do the global substitution.

grep -lr -e 'bad_method_name' * | xargs -n1 sed -i '' 's/bad_method_name/new_method_name/g'

As you we see in the code above we have our command starting with grep, looking for ‘bad_method_name’ in * and are piping that to sed.  With sed the only issue I had was with the -i flag.  At first I didn’t specify anything for that flag and had errors in OS X about a malformed sed command.  Passing a blank string to it fixed that.

Write a Comment