Changing the date format

Hi all,

I have a file with below data

af23b|11-FEB-12|acc7
ad23b|12-JAN-12|acc4
as23b|15-DEC-11|acc5
z123b|18-FEB-12|acc1

I need the output as below:-(date in yyyymmdd format)

af23b|20120211|acc7
ad23b|20120112|acc4
as23b|20111215|acc5
z123b|20120218|acc1

Please help me on this.
Thanks in adv.

If you have GNU date, try this:

while IFS='|' read a b c; do echo "$a|`date -d$b +%Y%m%d`|$c"; done < inputfile
1 Like

Dear Balajesuri,

Thanks for your reply. I have used the below command, but it is not working , i have korn shell, please help me for this..

awk '{while IFS='|' read a b c; do echo "$a|`date -d$b +%Y%m%d`|$c"; done}' < inputfile

Or , please give me a command which will convert the date 11-JAN-12 to 20120111

thanks

It's not working because you put that thing in an awk statement. Just put it as is on command line (ofcourse by substituting the filename to whatever contains your input)

Also, check if you have GNU date using this command: date --version

1 Like

Dear Balajesuri,

No, i dont have GNU date.
I am working in AIX system

#! /usr/bin/perl -w
use strict;

open I, "< inputfile";
for (<I>) {
    chomp;
    my @x = split /\|/;
    $x[1] = parse_date ($x[1]);
    print join ('|', @x), "\n";
}
close I;

sub parse_date {
    my $t = shift;
    my @d = split /-/, $t;
    my %mnths = (   "JAN" => "01", "FEB" => "02", "MAR" => "03", "APR" => "04", "MAY" => "05", "JUN" => "06",
                    "JUL" => "07", "AUG" => "08", "SEP" => "09", "OCT" => "10", "NOV" => "11", "DEC" => "12" );
    for (keys %mnths) { if ($d[1] eq $_) { $d[1] = $mnths{$_}; last } }
    return "20$d[2]$d[1]$d[0]";
}

I've hard-coded it to print "20" for the first 2 digits of year assuming you won't have to deal with the last or next century for now, atleast.

And, please start your posts by mentioning which system and shell you're working on. It helps in getting quicker answers.

1 Like

I know its dirty but worth to post.

$ mth=JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC
$ awk -F\| -v mlist=$mth '{split($2,A,"-") ;printf("%s|20%d%02d%d|%s\n", $1,A[3],(index(mlist,A[2])+2)/3,A[1],$3)}' x
af23b|20120211|acc7
ad23b|20120112|acc4
as23b|20111215|acc5
z123b|20120218|acc1
$

You having all caps in month name. Therefore my string looks dirty.
With standard 3 letters name, its looks "JanFebMarAprMayJunJulAugSepOctNovDec" . Somewhat meaningful.

1 Like
 
$ cat test.txt
af23b|11-FEB-12|acc7
ad23b|12-JAN-12|acc4
as23b|15-DEC-11|acc5
z123b|18-FEB-12|acc1
$ nawk -F\| -v OFS=\| 'BEGIN{M="  JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"}{split($2,a,"-");m=index(M,a[2])/3;if(m<10){m="0"m}$2="20"a[3]""m""a[1];print}' test.txt
af23b|20120211|acc7
ad23b|20120112|acc4
as23b|20111215|acc5
z123b|20120218|acc1