Insert a new line of text before a match of text

file-io, insertion, parsing, perl

Solution

This is a command-line version.

perl -i.bak -pe '$_ = qq[icecream: saturday\n$_] if $_ eq qq[icecream: sunday\n]' yourfile.txt

Explanation of command line options:

-i.bak : Act on the input file, creating a backup version with the extension .bak

-p : Loop through each line of the input file putting the line into $_ and print $_ after each iteration

-e : Execute this code for each line in the input file

Perl's command line options are documented in perlrun.

Explanation of code:

If the line of data (in $_) is "icecream: sunday\n", then prepend "icecream: saturday\n" to the line.

Then just print $_ (which is done implicitly with the -p flag).

Problem

In a text file, I'd like to insert a NEW line of text before each and every match of another line of text, using perl. Example - my file is: ``` holiday april icecream: sunday jujubee carefree icecream: sunday Christmas icecream: sunday towel ... ``` I would like to insert a line of text `'icecream: saturday'` BEFORE the '`icecream: sunday'` lines. So afterwards, the text file would look like. Yes, I DO need the colon `:` in both the searched and replaced pattern. ``` holiday april icecream: saturday icecream: sunday jujubee carefree icecream: saturday icecream: sunday Christmas icecream: saturday icecream: sunday towel ... ``` I'd like to do this using perl 5.14 on a Windows PC. I've already got Perl installed. I have searched and tried many of the other examples here on this website but they aren't working for me, and unfortunately I am not a complete expert of Perl. I've got Cygwin sed also if there is an example to use sed too.

Original source