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.

To:
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
done

1 comment:

Unknown 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
g/Bombay/s/Bombay/Mumbai/g
w
q
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:

http://www.amazon.com/Shell-Script-Pearls-Ron-Peters/dp/0615141056