February 19, 2009

HOW TO : Simple perl script to replace lines in file

Nothing fancy.. but here is a simple perl script to open a file, search for specific content in the a line and replace it with some other content.

open (SOURCE, "< source.xml") or die "Could not open file source.xml: $!\n"; open (DESTINATION, ">modfile.xml")
or die "Could not open file modfile.xml: $!\n";

while (defined($line =)) {
if ($line =~ m/YYYYYYYY/i) {
$line = "XXXXXXXXXXXXXXXXXXX\n";
}
print DESTINATION "$line";
}

close (SOURCE);
close (DESTINATION);

You are opening a file named source.xml, reading every line and if there is some text that matches “YYYYYYYY”, you are replacing the whole line with “XXXXXXXXXXXXXXXXXXX”. I am sure there are more elegant ways to write this :).. but this will do the trick too..