user3459532
user3459532

Reputation: 13

How to add string to exisiting file?

I am a beginner in perl language and I faced the above problem and would like to seek help in it. Much appreciate to all the help.

Given initial File Content:

Apple
Pear
Apple
Pear

Would like to have the output of:

Apple
Pear
Grape
Apple
Pear
Grape

Every time after pear is output, would like to add Grape to the output next.

Upvotes: 0

Views: 61

Answers (3)

user3459532
user3459532

Reputation: 13

Thanks guys for offering the help, i tried it out and i somehow manage to solve it by: Let say my file is in test1.

open(DATA,"<test1") or die "No test1 file";
while($data = <DATA>){
    if($data =~ /Pear/){
        $data = $data . "Grape\n";
    }
    print "$data";
}

Upvotes: 1

Miller
Miller

Reputation: 35198

Only because it's 4 characters shorter than mpapec's solution ;)

perl -pe 's/Pear\K/\nGrape/' file1.txt

If you really want to learn, try reading: How do I change, delete, or insert a line in a file, or append to the beginning of a file?

Upvotes: 1

mpapec
mpapec

Reputation: 50637

perl -pe '$_ .= "Grape\n" if /Pear/' file

Upvotes: 3

Related Questions