Wednesday, February 10, 2010

Isn't sed great

Search and replace using regex in multiple files from the command line. What more could a serious coder want.
sed -i.bak 's/foo/bar/g' *.cpp



ADDITION:

I Often find I want to just replace whole words. The way you do this will depend on the version of sed you're using.

This works for me on OS X
sed -i.bak 's/[[:<:]]foo[[:>:]]/bar/g' *.cpp
While on linux you can use the slighly neater
sed -i.bak 's/\<foo\>/bar/g' *.cpp

1 comment:

  1. I once had to convert a large amount of Ada code to C (about 30,000 lines in about 100 source files).

    Amazing how far a fairly ugly sed script could go in doing that. A few things like array indexing needed to be done by hand - Ada uses round brackets () for both arrays and function calls and uses context to figure out which means what. Doing that automatically requires a proper parser - a place I did not want to go.

    Sed is *very neat* once you know a few regex's.

    ReplyDelete