John Doe
John Doe

Reputation: 10203

Format date with a 3-char month name abbreviation using AWK

I have a datetime format as shown in the example below, which I want to convert to dd-mm-yyyy hh:mm:ss with AWK. How can I do this?

Current format:

3Jun2020 9:33:24; HG3456
7Jun2020 15:25:10; CH4747
10Jun2020 8:49:18; EU4821
12Jun2020 7:13:57; PP3478

Desired output:

03-06-2020 09:33:24; HG3456
07-06-2020 15:25:10; CH4747
10-06-2020 08:49:18; EU4821
12-06-2020 07:13:57; PP3478

Upvotes: 0

Views: 343

Answers (4)

Ed Morton
Ed Morton

Reputation: 204249

Using any awk in any shell on every Unix box:

$ cat tst.awk
BEGIN { FS=OFS=";" }
{
    split($1,t,/[ :]/)
    lgth    = length(t[1])
    dayNr   = substr(t[1],1,lgth - 7)
    mthAbbr = substr(t[1],lgth - 6,3)
    mthNr   = (index("JanFebMarAprMayJunJulAugSepOctNovDec",mthAbbr) + 2) / 3
    yrNr    = substr(t[1],lgth - 3)

    $1 = sprintf("%02d-%02d-%04d %02d:%02d:%02d", dayNr, mthNr, yrNr, t[2], t[3], t[4])
    print
}

$ awk -f tst.awk file
03-06-2020 09:33:24; HG3456
07-06-2020 15:25:10; CH4747
10-06-2020 08:49:18; EU4821
12-06-2020 07:13:57; PP3478

Upvotes: 2

sseLtaH
sseLtaH

Reputation: 11237

If sed is an option, you can execute the date command within the replacement.

$ sed "s/\([^;]*\)\(.*\)/\date -d '\1' '+%d-%m-%Y %T\2'/e" input_file
03-06-2020 09:33:24; HG3456
07-06-2020 15:25:10; CH4747
10-06-2020 08:49:18; EU4821
12-06-2020 07:13:57; PP3478

Upvotes: 1

Suraj Kumar Nanda
Suraj Kumar Nanda

Reputation: 59

perl -MPOSIX -MDate::Parse -pe 's{^\S+\s+\S+(?=;)}{strftime("%d-%m-%Y %T", strptime($&))}e; s/^0//' file

Upvotes: 1

Daweo
Daweo

Reputation: 36680

I would use GNU AWK for this task following way, let file.txt content be

3Jun2020 9:33:24; HG3456
7Jun2020 15:25:10; CH4747
10Jun2020 8:49:18; EU4821
12Jun2020 7:13:57; PP3478

then

awk '{sub(/Jan/,"-01-",$1);sub(/Feb/,"-02-",$1);sub(/Mar/,"-03-",$1);sub(/Apr/,"-04-",$1);sub(/May/,"-05-",$1);sub(/Jun/,"-06-",$1);sub(/Jul/,"-07-",$1);sub(/Aug/,"-08-",$1);sub(/Sep/,"-09-",$1);sub(/Oct/,"-10-",$1);sub(/Nov/,"-11-",$1);sub(/Dec/,"-12-",$1);print}' file.txt

output

3-06-2020 9:33:24; HG3456
7-06-2020 15:25:10; CH4747
10-06-2020 8:49:18; EU4821
12-06-2020 7:13:57; PP3478

Explantion: replace Jan using -01-, Feb using -02-, Mar using -03- and so on, then print. Disclaimer: code might need adjusting if you use other locale.

(tested in GNU Awk 5.0.1)

Upvotes: 1

Related Questions