需要得到一年中所有星期一的date

我需要在每周的基础上sorting数据,我所有的日志都在日志文件中。 因此,要每周清理数据,我想创build一个给定年份所有星期几的列表。 我试图解决一些问题,我现在唯一的想法就是使用年份和月份的ncal作为参数循环遍历所有月份并提取所有星期一。 没有更有效的方法吗?

Solutions Collecting From Web of "需要得到一年中所有星期一的date"

要获取所有星期一,通过获取所有日期和星期一过滤:

for i in `seq 0 365` do date -d "+$i day" done | grep Mon 

当然,你也可以在星期一继续增加7天。

希望这就是你的意思。 以下可以改变,以改变日期的输出格式。

日期命令可以用于这一点,不知道如果ncal是多/少效率。

我知道你现在去了“分档”,但这是一个更可读的v。

 $ cat /tmp/1.sh #!/bin/bash test -z "$year" && { echo "I expect you to set \$year environment variable" echo "In return I will display you the Mondays of this year" exit 1 } # change me if you would like the date format to be different # man date would tell you all the combinations you can use here DATE_FORMAT="+%Y-%m-%d" # change me if you change the date format above. I need to be # able to extract the year from the date I'm shoing you GET_YEAR="s/-.*//" # this value is a week, in milliseconds. Changing it would change # what I'm doing. WEEK_INC=604800 # Use another 3-digit week day name here, to see dates for other week days DAY_OF_WEEK=Mon # stage 1, let's find us the first day of the week in this year d=1 # is it DAY_OF_WEEK yet? while test "$(date -d ${year}-1-${d} +%a)" != "$DAY_OF_WEEK"; do # no, so let's look at the next day d=$((d+1)); done; # let's ask for the milliseconds for that DAY_OF_WEEK that I found above umon=$(date -d ${year}-1-${d} +%s) # let's loop until we break from inside while true; do # ndate is the date that we testing right now ndate=$(date -d @$umon "$DATE_FORMAT"); # let's extract year ny=$(echo $ndate|sed "$GET_YEAR"); # did we go over this year? If yes, then break out test $ny -ne $year && { break; } # move on to next week umon=$((umon+WEEK_INC)) # display the date so far echo "$ndate" done 

一年中无需重复365天或366天。 以下执行date最多71次。

 #!/bin/bash y=2011 for d in {0..6} do if (( $(date -d "$y-1-1 + $d day" '+%u') == 1)) # +%w: Mon == 1 also then break fi done for ((w = d; w <= $(date -d "$y-12-31" '+%j'); w += 7)) do date -d "$y-1-1 + $w day" '+%Y-%m-%d' done 

输出:

 2011-01-03 2011-01-10 2011-01-17 2011-01-24 2011-01-31 2011-02-07 2011-02-14 2011-02-21 2011-02-28 2011-03-07 . . . 2011-11-28 2011-12-05 2011-12-12 2011-12-19 2011-12-26 

另一个选项,我已经根据上述答案。 现在可以指定开始和结束日期。

 #!/bin/bash datestart=20110101 dateend=20111231 for tmpd in {0..6} do date -d "$datestart $tmpd day" | grep -q Mon if [ $? = 0 ]; then break fi done for ((tmpw = $tmpd; $(date -d "$datestart $tmpw day" +%s) <= $(date -d "$dateend" +%s); tmpw += 7)) do echo `date -d "$datestart $tmpw day" +%d-%b-%Y` done 

您可以使用date获取当前的周数。 也许你可以排序:

 $ date +%W -d '2011-02-18' 07