FreeKB - Replace values in a file in Perl
Replace values in a file in Perl

Home > Search


There are multiple ways to replace text in a file in Perl. Let's say example.txt contains the following lines of text.

apple
orange
grape
pineapple

 

I like to first store the content of the file in an array. In this example, the @fruit array will contain apple orange grape pineapple.

open(FH, "<", "/path/to/example.txt") or die "cannot open file $! \n";
my @fruit = <FH>;
close FH;

 

Then I use the map operator to update the array. In this example, "orange" is replace with "peach".

map { s/orange/peach/g } @fruit;

 

Then the file is overwritten to contain the values in the array.

my $file = "/path/to/file.txt";
open(FH, ">", "$file") or die "cannot open $file $! \n";

foreach my $line (@fruit) {
  print FH "$line";
}

close FH;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments