Regular expression in Perl (how to replace a date string)
Posted by Faiz on February 1st, 2009 filed in Perl SupportIn Perl you can replace a string easily, than your normal counterpart SED editor. With SED you would have to use the -e flag in order to edit the content of your data - then pipe it to a new output file and then finally rename the new output file the appropriate file name again. With Perl this becomes simple to do. All you do is use the Perl -i flag this is a Perl internal that will automatically create a backup of the original file you - all you do is give the backup file name extension. Look at my scripts first line.
Since this is hard coded routine, I have made the variables local to my routine
Code below!!!!!
============
#!/usr/bin/perl -i.bkup
use strict;
use warnings;
system(’clear’);
#Declare + Initialization;
#=========================
my $replace_OLD=’2008/02/03′;
my $replace_NEW=’2009/01/20′;
my $num_of_args = @ARGV;
# Print the usage out !!!!
#=========================
print “nnComment: Number of arguments is: $num_of_argsn”;
# Verify number of arguments if zero just exit!!!!
#=================================================
if ($num_of_args == 0)
{ print “nnERROR: No command line arguments passed to the script $0 n”;
print “USAGE: n”;
print ‘Example 1 : ./Replace_Dates.pl inputfile’,”n”;
print ‘Example 2 : ./Replace_Dates.pl /dsk1_app/sys1/*.DAT’,”n”;
exit;
}# END_if
# Now loop through those records !!!!
#=====================================
while (
{
s/$replace_OLD/$replace_NEW/g;
print;
} # END_while
print “nDONE. Script: $0n”;