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

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;
}

 



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 8cac4 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |