我想指定一个时间范围并在 bash 中计算该范围内的工作日。我发现这剪断了并将其编辑为 2020 年 1 月和 2 月印刷:
#!/bin/bash
startdate=2020-01-01
enddate=2020-02-28
curr="$startdate"
while true; do
echo "$curr"
[ "$curr" \< "$enddate" ] || break
curr=$( date +%Y-%m-%d --date "$curr +1 day" )
done
现在我只想打印这个范围内的所有星期一,我该怎么做?
我想echo "$curr"
用类似:echo "$curr" | date +%Y-%m-%d-%a
或不带回显的内容替换:date +%Y-%m-%d-%a <<< "$curr"
将工作日添加到输出中,然后用或%a
过滤星期一并对其进行计数。尽管我以这种方式格式化输出的方法不起作用。sed
awk
答案1
怎么样
startdate=2020-01-01
enddate=2020-02-28
mondays=()
# what day of week is startdate? Sun=0, Sat=6
dow=$(date -d "$startdate" "+%w")
# the date of the first monday on or after startdate
# if you want Tuesdays, change "1" to "2", and so on for other days.
monday=$(date -d "$startdate + $(( (7 + 1 - dow) % 7 )) days" "+%F")
# find all mondays in range
until [[ $monday > $enddate ]]; do
mondays+=( "$monday" )
monday=$(date -d "$monday + 7 days" "+%F")
done
printf "%s\n" "${mondays[@]}"
输出
2020-01-06
2020-01-13
2020-01-20
2020-01-27
2020-02-03
2020-02-10
2020-02-17
2020-02-24