user1864091
user1864091

Reputation: 51

Insert a new line of text before a match of text

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.

Upvotes: 5

Views: 8064

Answers (3)

Dave Cross
Dave Cross

Reputation: 69264

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).

Upvotes: 9

Kenosis
Kenosis

Reputation: 6204

Here's an option using the File::Slurp Module:

use strict;
use warnings;
use File::Slurp qw/:edit/;

edit_file sub { s/(icecream: sunday)/icecream: saturday\n$1/g }, 'data.txt';

And an option not using that Module:

use strict;
use warnings;

open my $fhIn,  '<', 'data.txt'          or die $!;
open my $fhOut, '>', 'data_modified.txt' or die $!;

while (<$fhIn>) {
    print $fhOut "icecream: saturday\n" if /icecream: sunday/;
    print $fhOut $_;
}

close $fhOut;
close $fhIn;

Upvotes: 2

David
David

Reputation: 6571

open FILE, "<icecream.txt" or die $!;
my @lines = <FILE>;
close FILE or die $!;

my $idx = 0;
do {
    if($lines[$idx] =~ /icecream: sunday/) {
        splice @lines, $idx, 0, "icecream: saturday\n";
        $idx++;
    }
    $idx++;
} until($idx >= @lines);

open FILE, ">icecream.txt" or die $!;
print FILE join("",@lines);
close FILE;

Upvotes: 2

Related Questions