In Unix, I want to find the date (day of month) of the last Saturday of a given month and year. I know cal
will give me the calendar for a given month / year. What is a good way to get the last Saturday?
Update: I'd like a solution that I could use to apply to any day of the week. For example, I could use the same method to find the date of the last Sunday or Wednesday as well.
Use awk for that. Consider this:
OUTPUT:
I have another answer for this question, which is a bit lengthy Bash script and not so efficient, but easy to understand. The basic idea is it to loop over the days 22 till 31 for the given month and year and check the day of the week for each of these days by
date +'%u'
. The last day for which this returns the wanted week day (e.g. Saturday) is stored in the variableRESULT_DAY
, which will contain the result after the loop.We check for
date
's result code by checking$?
for value "0", so we can ignore illegal days (e.g. 31st of February, which does not exist).The 22nd day of a month is the earliest date we have to consider, because in the shortest month (February in non-leap years) this is the earliest day for the last occurrence of a e.g. Saturday.
If you didn't want to just pipe/parse
cal
output, you could use an algorithm to determine the weekday of a date, then get the weekday for December 31st and move backward the number of days needed to make it a Saturday.But parsing cal is probably simpler.