by

Using Perl and Regular Expressions to Find and Replace Text

The following Perl script uses regular expressions to parse a text file called myFile.txt and replace any occurrence of the character sequence REPLACE with the string (or number) stored in $NEWTEXT. The modified text file is saved as myNewFile.txt.

#!/usr/bin/perl
$NEWTEXT = "New Stuff"; # could also be a number

open(INPUT, "< myFile.txt") or die ("Can't open input file.\n");
open(OUTPUT, "> myNewFile.txt");

select(OUTPUT); # print to the output file instead of the screen

while(<INPUT>) {
   $_ =~ s/REPLACE/$NEWTEXT/;
   print $_; 
}
close(INPUT) or die ("Can't close input file.\n");
close(OUTPUT) or die ("Can't close output file.\n");

Leave a Reply

Your email address will not be published. Required fields are marked *