Home > Net >  awk on a date variable
awk on a date variable

Time:03-04

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"}'

CodePudding user response:

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 "ddd\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

CodePudding user response:

Your original example uses awk to prepare arguments that are then passed to the Linux date command running in bash; the date formatting is performed by the date command.

You don't need awk for this, the date command -d option is very flexible in the format it receives.

mydate="Oct 3 2021"
date -d "$mydate"  %Y%m%d

Will give you a formatted date. You can assign the result to a variable using the $() syntax - run a command and assign result

formattedDate=$(date -d "$mydate"  %Y%m%d)
echo $formattedDate
  • Related