-2

Input :

01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"

Expected output :

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

How do I convert the abbreviated month name to month number and achieve the expected output?

James Brown
  • 36,089
  • 7
  • 43
  • 59
pavithra
  • 83
  • 12
  • 1
    Possible duplicate of [Unix convert Month name to number](https://stackoverflow.com/questions/15252383/unix-convert-month-name-to-number) – Gino Mempin May 29 '19 at 05:46

3 Answers3

2

you mean something like this?

#!/bin/bash
while  read -r line; do
   # use date to convert first column of line
   newdate=$(date -d "${line%%|*}" +"%d-%m-%y")

   # print new date and the last two columns
   printf "%s|%s\n" "$newdate" "${line#*|}"
done < input   
UtLox
  • 3,744
  • 2
  • 10
  • 13
1

Using GNU awk (easily converted to other awks by ditching strftile() and related (ie. lines 3-5) and defining m["JAN"]="01";m["FEB"]="02";etc.):

$ awk 'BEGIN {                                             # prime a hash for month abbr.
    FS=OFS="-"                                             # split at -
    Ms=28*24*60*60                                         # "month seconds"
    for(t=1;t<=12;t++)                                     # iterate all month numbers
        m[toupper(strftime("%b",t*Ms))]=sprintf("%02d",t)  # hash m["JAN"]="01"
}
{
    $2=m[$2]                                               # retrieve month # from hash
}1' file                                                   # output

Output with your data:

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

For a million records of your data this script ran 1.7 s:

real    0m1.719s
user    0m1.688s
sys     0m0.032s
James Brown
  • 36,089
  • 7
  • 43
  • 59
1

A brute-force method with arrays:

awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        n = split("JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC", s)
        for (i=1; i<=n; i++)
            m[s[i]] = sprintf("%0.2i", i)
    }
    { $2 = m[$2]; print }
    ' file

Really brute force (& dead simple):

awk '
    BEGIN {
        FS = OFS = "-"
        split("", m)
        m["JAN"] = "01"
        m["FEB"] = "02"
        m["MAR"] = "02"
        m["APR"] = "03"
        m["MAY"] = "05"
        m["JUN"] = "06"
        m["JUL"] = "07"
        m["AUG"] = "08"
        m["SEP"] = "09"
        m["OCT"] = "10"
        m["NOV"] = "11"
        m["DEC"] = "12"
    }
    { $2 = m[$2]; print }
    ' file

Or using index:

awk -F- -v OFS=- '{
    m = index("  JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", $2) / 3
    $2 = sprintf("%0.2i", m)
    print
}' file
Michael Back
  • 1,821
  • 1
  • 16
  • 17