Search and replace from command line

I usually do my find and replaces from within VIM or Eclipse (refactoring).

It may be useful to do it from the command line in case you don’t want to (or cannot) open your editor or if you need to work on a larger set of files (e.g.: scripts, meta-languages that Eclipse won’t refactor, etc).

The following command will recursively find all the *.cpp, *.h and *.c files starting from the current directory and change every occurrence of the pattern (in this case just a string) “createAndSet” with “init” (IMPORTANT: read the WARNING notice below before using the command):

find . -name *.c -o -name *.cpp -o -name *.h | xargs sed -i.bak 's/createAndSet/init/g'

The -i option tells sed to edit files in place and the optional parameter “.bak” tells sed to create backup files with a “.bak” suffix. By removing the “-i” option, sed will just output the result to stdout.

Warning

Use the command above judiciously, it may be disruptive and change your code in ways you do not expect.

Sed will replace every occurrence of a regular expression. If you want to change every occurrence of the string “int” to “long int” and you try to use the substitution “s/int/long int/g“, then every occurrence of a “printf” call will become “prlong intf”.

Test the regular expressions and observe their effect by calling sed in “dry run” mode, without the “-i” option (no in-place editing).

I cannot be responsible for any damage caused by the usage of the above command or a similar one :)!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s