May 5, 2008

Inline Search and Replacement One Liners

Here are two ways to do inline file replacement of patterns using perl and sed. Both examples will do a global replacement of the string orig with the string replacement.

First, we have a perl one liner:
perl -pi -e 's/orig/replacement/g' file

And here we do the same with sed:
sed -i -e 's/orig/replacement/g' file

This example finds and replaces a simple string in a file. You can also use a regex (regular expression) to do more powerful substitutions.

To replace all words that begin abb with ABB in /usr/share/dict/words:
sed -i -e 's/^abb/ABB/g' /usr/share/dict/words

$ egrep '^abd' /usr/share/dict/words
abdomen
abdomens
abdominal
abduct
abducted
abduction
abductions
abductor
abductors
abducts
$ sed -i -e 's/^abb/ABB/g' /usr/share/dict/words
$ egrep '^abb' /usr/share/dict/words
$ egrep '^ABB' /usr/share/dict/words
ABBe
ABBey
ABBeys
ABBot
ABBots
ABBreviate
ABBreviated
ABBreviates
ABBreviating
ABBreviation
ABBreviations
$

Of course I used a copy of the words file and didn't actually clobber the original.

1 comment:

joy said...

Good day! I was so impressed to see a very well-presented dishes that is absolutely tasty and delicious. You've done a great job.Well, thank you for sharing your talent and article it is very well appreciated. You can also visit my site if you have time.

n8fan.net

www.n8fan.net