user8060151
user8060151

Reputation:

How do I update a line in a file using Perl?

I need update specific line in file.

I use regular expression. Finally, I run over next line. The file dog2cat contains:

This example
The dog is drinking.
It is drinking milk.

My code:

open(FILE,"+<dog2cat");
while(<FILE>)
{
  my $line=$_;
  if($line =~ /dog/)
  {
    $line =~ s/dog/cat/;
    print FILE $line; 
  }
}
close FILE;

Finally the file contain

This example
The dog is drinking.
The cat is drinking.

I want to get

This example
The cat is drinking.
It is drinking milk.

Upvotes: 0

Views: 636

Answers (2)

stevieb
stevieb

Reputation: 9296

For simple file update tasks, you can use a Perl "one-liner":

perl -i -pe 's/dog/cat/g' dogcat.txt

The -i says to update the file you're working on (you can add an extension to it if you want to write to a new file. For example, -i.bak will write to a file named dogcat.txt.bak).

The -p says iterate over each line, and print it out (with -i, print back to the file).

-e executes whatever is between the quotes on each line in the file.

Upvotes: 2

Eric McNeill
Eric McNeill

Reputation: 1814

Open a second file for output, print to that one. Or print to the screen instead of another file, and when you run your script pipe the output into a file.

Upvotes: 1

Related Questions