awk switch

Updated: 19 March 2024

Convert month short name to number

switch(month_str){
    case "Jan":
        month_num="01"
        break
    case "Feb":
        month_num="02"
        break
    case "Mar":
        month_num="03"
        break
    case "Apr":
        month_num="04"
        break
    case "May":
        month_num="05"
        break
    case "Jun":
        month_num="06"
        break
    case "Jul":
        month_num="07"
        break
    case "Aug":
        month_num="08"
        break
    case "Sep":
        month_num="09"
        break
    case "Oct":
        month_num="10"
        break
    case "Nov":
        month_num="11"
        break
    case "Dec":
        month_num="12"
        break
    }

awk

Updated: 24 February 2024

Basic format of an awk command

awk '/search_pattern/ { action_to_take_on_matches; another_action; }' file_to_parse

Run awk script in a file

awk -f source.awk input-file1 input-file2 ...

General form of an awk script in a file

BEGIN { action; }
/search/ { action; }
END { action; }

Script in file, with user defined function. Ignore first row of a pipe delimited file. This example creates SQL statements

# convert 13/01/2022 format to 2022-01-13
function format_date(raw_date)
{
    split(raw_date, a, "/");
    return a[3] "-" a[2] "-" a[1];
}

BEGIN { FS="|"; }
NR>1 { 
    print "INSERT INTO payments (payment_date, payment_from, payment_ammount) VALUES ('" format_date($2) "', '" $6 "', "$4");";
    print "INSERT INTO payment_invoice (payment_id, invoice_id) VALUES (last_insert_id(), " $7 ");"
}
END { }