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 { }

Leave a comment