Date conversion in row while preserving rest of fields

Hi Forum.

I searched the forum for a solution but could not find an exact one to my problem.

I have some records in the file where I would like to convert the last date field to another format while preserving the rest of the other fields.

For example:

Found:
00000000|2011-Inactive-Segment|2|1|03/15/2011 0:00:00

Expected:
00000000|2011-Inactive-Segment|2|1|15-MAR-2011

Please help.

Thanks.

nawk -F'|' -f pc.awk OFS='|' myFile

pv.awk:

BEGIN {
   mon="JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC"
   monN=split(mon, monA, "|");
}
{
  n=split($NF,a,"[/ ]")
  $NF=sprintf("%02d-%s-%d",a[2], monA[a[1]+0], a[3])
}
1
1 Like

This will be much easier on some systems than others. Are you running Linux? do you have GNU awk?

Hi Corona688.

I'm running on an AIX box - how do I check for the awk version?

Thanks Vgersh for your solution - I will give it a try.

I don't think AIX has GNU awk, but it may have a nawk which is newer than the basic awk anyway. But vgersh' clever solution might be minimal enough to work in any. It's sometimes hard to tell what an old awk will throw up on though, so nawk gets suggested first.

On linux this is redundant, awk and nawk and gawk will all be the same full-featured GNU awk.

Vgersh99.

Your code solution was awesome and works great.

Would you mind explaining the awk code portion?

I would like to understand the code better.

BEGIN {
   mon="JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC"
   # Create an array where mon[1]=JAN, mon[2]=FEB, etc.
   monN=split(mon, monA, "|");
}
{
  # NF is the number of fields, $NF is the very last field.
  # So split the very last field into an array on the / or ' ' chars.
  n=split($NF,a,"[/ ]")
  # convert months 1-12 into JAN-DEC by looking them up in monA.
  # then print the whole mess in the format below, just like C or shell printf.
  $NF=sprintf("%02d-%s-%d",a[2], monA[a[1]+0], a[3])
}
# When the following expression is true, lines are printed.
# 1 is always true, so it prints every line.
1
2 Likes