Hi All,
I am learning PERL for one of the projects, and in one of these scripts, I read a flat text file and print in the terminal.
The problem is, the text file has a date field. The format is yyyymmdd. I need to display this as dd-mon-yyyy.
Any ideas to do this? Thanks a lot for the help.
Regards
Guru
--------------------------------------------------------------------------
Note: I wrongly tagged this as PERL DATE::MANIP. Looks like I need to download and use this. Is it not included in standard distribution. If not, I can't use it to.
We can easily do that by using regular expression in Perl.
$line="20091029 Text File";
$line=~/([0-9]{4})([0-9]{2})([0-9]{2}).*/;
print "$3-$2-$1";
open FH,"<date_file";
my $full_date = <FH>;
chomp($full_date);
if ( $full_date =~ /^([0-9]{4})([0-9]{2})([0-9]{2})/)
{
print "$3-$2-$1\n";
}
consider that the date_file is having the data as
20100305 which is in yyyymmdd format.
Now the above script's print statement will print the output as
05-03-2010 which is in the dd-mm-yyyy format.
You can do this simply by the substitution.
use strict;
use warnings;
open FH , "<test"; # test is the file
while(<FH>)
{
$_=~s/([0-9]{4})([0-9]{2})([0-9]{2})/$3-$2-$1/g;
print $_;
}
If the regex
means 20100205 to 05-02-2010, then it is wrong. I am looking for 05-FEB-2010.
For this,you can use the hash in your perl program.
%hash=("01"=>"Jan","02"=>"Feb","03"=>"Mar","04"=>"Apr","05"=>"May","06"=>"Jun","07"=>"Jul","08"=>"Aug","09"=>"Sep","10"=>"Oct","11"=>"Nov","12"=>"Dec");
$line="20090329 Text File";
$line=~/([0-9]{4})([0-9]{2})([0-9]{2}).*/;
print "$3-$hash{$2}-$1";
use strict;
open FH , "<test";
my %hash=("01"=>"JAN","02"=>"FEB","03"=>"MAR","04"=>"APR","05"=>"MAY","06"=>"JUN","07"=>"JUL","08"=>"AUG","09"=>"SEP","10"=>"OCT","11"=>"NOV","12"=>"DEC");
while(<FH>)
{
if(/([0-9]{4})([0-9]{2})([0-9]{2})/)
{
print $3."-".$hash{$2}."-".$1 ."\n";
}
}
use strict;
use warnings;
my %hash=( 1=> "JAN",
2=>"FEB",
3 => "MAR",
4 =>"APR",
5=> "MAY",
6 => "JUN",
7 => "JUL",
8 => "AUG",
9 => "SEP",
10 => "OCT",
11 => "NOV",
12 => "DEC"
);
my $line="20091029 Text File";
$line=~/([0-9]{4})([0-9]{1,2})([0-9]{2}).*/;
print "$1 -$hash{$2}- $3";
pludi
March 5, 2010, 5:40am
9
A simple regex won't suffice, as it won't translate the month number to it's name. Try this:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw/strftime/;
my $date = "20100205";
if ( $date =~ /(\d{4})(\d{2})(\d{2})/ ) {
print strftime( "%d-%b-%Y", 0, 0, 0, $3, $2, $1 - 1900 );
}
The POSIX module is part of the base distribution.
Thanks to, Vivek and Karthigayan, for your timely help.