shellunix

How to convert month name to number in unix?


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?


Solution

  • 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