问题
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.
回答1:
Use awk for that. Consider this:
cal 5 2013 | awk 'NF>6{a=$7} END{print a}'
OUTPUT:
25
回答2:
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.
回答3:
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 variable RESULT_DAY
, which will contain the result after the loop.
#!/bin/bash
DAY_OF_WEEK=6 # 1=Monday, ..., 7=Sunday
THE_YEAR=2016
THE_MONTH=10
RESULT_DAY=0
YEAR_MONTH_STR=${THE_YEAR}"-"${THE_MONTH} # Example value: "2016-10"
for DAYNO in 22 23 24 25 26 27 28 29 30 31
do
DATE_TO_CHECK=${YEAR_MONTH_STR}"-"${DAYNO}
DATE_RESULT=$(date --date=$DATE_TO_CHECK '+%u')
if [ $? -eq 0 ]
then
if [ $DATE_RESULT -eq $DAY_OF_WEEK ]
then
RESULT_DAY=$DAYNO
fi
fi
done
RESULT_DATE_COMPLETE=${YEAR_MONTH_STR}"-"${RESULT_DAY}
echo -e "\nResult date (YYYY-MM-DD): "$(date --date=$RESULT_DATE_COMPLETE +'%Y-%m-%d (%A)')
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.
来源:https://stackoverflow.com/questions/10436146/the-last-saturday-of-a-given-month-year