I needed to find a simple way to search for a pattern of text on one line in a file and replace it with two lines of text. I could not find any editor like Vi or sed or awk that could do it easily. I'm betting they can though. These editors would do a pattern match in the search area but when it came to the replace area it would not take the same type of replace commands like a new line (\n) command. So of course Perl comes to the rescue and it's as easy as pie. Below is the example of how to do it. The line is executed from a shell and finds the word "test" and replaces it with the word test1 and test2 both on seperate lines. After the substitution it backs up the orginal file specified at the end (the word "file" below) with the extention .bak. You can also use a "*" instead a file name so it will work on all the files in a directory.
perl -i.bak -pe 's/test/test1\ntest2/' file
Really it's put best from Perl.com on different ways to use this feature of Perl:
perl -pe 'some code' < input.txt > output.txt
This takes records from input.txt, carries out some kind of transformation, and writes the transformed record to output.txt. In some cases you don't want to write the changed data to a different file, it's often more convenient if the altered data is written back to the same file.
You can get the appearance of this using the -i option. Actually, Perl renames the input file and reads from this renamed version while writing to a new file with the original name. If -i is given a string argument, then that string is appended to the name of the original version of the file. For example, to change all occurrences of "PHP" to "Perl" in a data file you could write something like this:
perl -i -pe 's/\bPHP\b/Perl/g' file.txt
Perl reads the input file a line at a time, making the substitution, and then writing the results back to a new file that has the same name as the original file -- effectively overwriting it. If you're not so confident of your Perl abilities you might take a backup of the original file, like this:
perl -i.bak -pe 's/\bPHP\b/Perl/g' file.txt