Sunday, April 29, 2007

Search and replace Shell Script

Had to parse 100's of files in a loop and replace a word
called Bombay with a new word Mumbai

cat file1.dat
city name is Bombay and country is INDIA.

cat file1.dat
city name is Mumbai and country is INDIA.

for file in /tmp/a /tmp/c /tmp/b ; do
sed 's/Bombay/MUMBAI/g' ${file} > ${file}.new

1 comment:

Ron said...

If you wanted to modify the files in place, you could have used ed instead of sed and done something like this:

ed -s /target/file [[EOF

You will have to replace the [[ with less-than less than. I couldn't find the correct syntax for this editor so it wouldn't interpret them as html.

The downside is that instead of making a modified copy of the file, you're editing the file directly.

I just published a scripting book and I talk about this technique in Chapter 25. It can be found at Amazon and other sites: