Bootstrap FreeKB - Perl (Scripting) - Replace values in a file
Perl (Scripting) - Replace values in a file

Updated:   |  Perl (Scripting) articles

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.

my @fruit;
if (open FH, "<", "foo.txt") {
  @fruit = <FH>;
  close FH;
}
else {
  print "failed to open foo.txt \n";
  exit 1;
}

 

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.

if (open FH, ">", "foo.txt") {
  foreach my $line (@fruit) {
    print FH "$line";
  }
  close FH;
}
else {
  print "failed to open foo.txt \n";
  exit 1;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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