awk on a date variable

jimbolino

What is working :

echo "Oct 12 2021" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash

how could I use a variable on a bash script ?

mydate="Oct 12 2021"
awk -v dateformat= ''$mydate" '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}'
Ed Morton

You obviously wouldn't really use awk to call date on a single value but I assume you have something more than that in mind in your real code so this is what you asked for (call GNU date from awk using an awk variable as the date):

mydate="Oct 12 2021"
awk -v date="$mydate" 'BEGIN {
   system("date -d\047" date "\047 +\047%Y%m%d\047")
}'
20211012

or if you prefer:

awk -v date="$mydate" 'BEGIN {
    cmd = "date -d\047" date "\047 +\047%Y%m%d\047"
    print ( (cmd | getline line) > 0 ? line : date"=N/A" )
    close(cmd)
}'
20211012

Don't do either of those though. It's very slow to call an external command from awk and you don't need to when all you want to do is change text from one format to another:

$ awk -v date="$mydate" 'BEGIN {
    split(date,d);
    mth = (index("JanFebMarAprMayJunJulAugSepOctNovDec",d[1])+2)/3
    printf "%04d%02d%02d\n", d[3], mth, d[2]
}'
20211012

Also, if you have GNU awk it has built-in time functions so even if what you wanted to do wasn't just shuffling bits of text around you could call the internal mktime() and strftime() instead of the external date:

awk -v date="$mydate" 'BEGIN {
    split(date,d)
    mth = (index("JanFebMarAprMayJunJulAugSepOctNovDec",d[1])+2)/3
    secs = mktime(d[3]" "mth" "d[2]" 12 0 0")
    print strftime("%Y%m%d",secs)
}'
20211012

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related