Perl Pie: If you only learn how to do one thing with Perl, this is it.

May 21 2009

Ever run into that situation where you need to run a find-and-replace inside of multiple documents? Ever wanted to do this with a regular expression, without having to use any complex sed redirection? Here's a pattern for doing this in perl.

No, you don't need to be a Perl guru to use this command. in fact, you don't really need to know Perl at all. If you know regular expressions and can type a command in a shell prompt, you are good to go.

Here's the pattern:

$ perl -pi -e '<some replacement regular expression>' <file or files>

The pattern above is used for running an inline replacement using regular expressions. Given the -pi -e flags, this pattern is sometimes called "perl pie".

Here is an example that replaces MY_NAME with Matt in any files in the current directory that end with the txt extension:

$ perl -pi -e 's/MY_NAME/Matt/g' ./*.txt

When executed, this will seek all files matching ./*.txt and run the replacement pattern s/MYNAME/Matt/g. This regular expression simply replaces all occurrences of MYNAME with Matt. This is a simple example, but in your own scripts you can draw freely from the hefty regular expression syntax for which Perl is famous. (Check out man perlre or the wealth of regular expressions websites for more.)

So let's take a look at what happens when the above is run. Here's one of the text files before the above command is executed:

Hello, my name is MY_NAME. Have a nice day.

After running the Perl command, the above file looks like this:

Hello, my name is Matt. Have a nice day.

And that, in a nutshell, is the one line of Perl that you really ought to know. <!--break-->