1

According to link last day can be seen using this date command:

$ date -d "-$(date +%d) days -1 month"
Wed May 31 21:20:31 CEST 2017

My question is, how can I get only the day and assign it to a variable, which I'll later use, like

awk '{day=system("date -d \"-$(date +%d) days -1 month\")"; print day)}' 

so for example printing day will output only 31. I know that date format needs to be formatted, but I fail to understand how to print only the last day from it.

Or if there is another simpler method in awk it will do job as well.

EDIT Some very dirty workaround..

$ awk '{a=system("date -d \"-$(date +%d) days -1 month\"| cut -f 3 -d \" \""); }END{print a}'

31

Anyone has simpler/cleaner idea?

  • $ date -d "-$(date +%d) days -1 month" +%d to simply format the outer invocation of date perhaps? – DopeGhoti Jul 12 '17 at 20:45
3

Last day of current month should be:

$ date -d "$(date +%Y-%m-01) +1 month -1 day"
Mon Jul 31 00:00:00 CEST 2017

My shortest:

awk '{a=system("date -d \"$(date +%Y-%m-01) +1 month -1 day\" +%d")}END{print a}'
1

Just use a format string for the outer invocation of date:

$ date -d "-$(date +%d) days +1 month" +%d
31
  • +1 ... although I think it needs to be + 1 month if the OP really wants the last day of the current month; possibly "next month - $(date +%d) days" captures the intent more clearly – steeldriver Jul 12 '17 at 20:50
0

Try this:

month=$(cal 07 2017)
lastday=${month: -24: 2}
echo $lastday

I'm using the calendar function to load the "month" variable with all of the days of the month and then picking off the last two characters. The example is for July of 2017 but it works with and month/year.

0
lastday=$(cal 07 2017|awk 'END{print day};{if (NF>0){day=$NF}}')

This plucks the last day value of the calendar's last line, ignoring blank lines.

A bit shorter is:

lastday=$(cal 07 2017|awk 'END{print day};{NF>0 && day=$NF}')
  • I need to get a day in awk script explicitly, so i can use it with awk, not with bash/shell. I am checking awk 'strftime()' function, but have no clue how to use it for my purpose. – fugitive Jul 12 '17 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.