Friday, February 22, 2008

Linux search and replace in files

So you want to replace a regular expression in multiple files under Linux?

Well, there are two convenient ways this can be done with a single line from a shell.

First, you can use SED

sed -i -e 's/source/destination/g' *.txt

"source" is of course the part to search for, and "destination" is what you want it replaced to. Also replace *.txt with whatever.

The second solution is to use perl

perl -pi -e 's/source/destination/g' *.txt

If you want something really nasty, you can use perl mixed with the 'find' command

perl -pi -e 's/source/destination/g' `find . -name '*.txt'`

Note the different quotes here... Might be a bit tricky to find, depending on your keyboard layout. This lets you replace in the files found by the find command, and is a quite powerful form of search and replace.

No comments: