需要获取一年中所有星期一的日期

时间:2011-02-18 07:46:50

标签: linux bash shell date

我需要在每周基础上对数据进行排序,而我所拥有的只是日志文件中的日期。 因此,为了每周整理数据,我想创建一个列表,其中包含给定年份所有星期一的日期。我试图解决一些问题,我目前唯一的想法是使用年份和月份的ncal作为参数循环所有月份并提取所有星期一。是不是有更有效的方式?

5 个答案:

答案 0 :(得分:4)

通过获取所有日期并按星期一过滤来获取所有星期一:

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

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

答案 1 :(得分:3)

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

日期命令可用于此,如果ncal更高/效率更低,则为dunno。

我知道你现在去了“binning”,但这里有一个更具可读性的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

答案 2 :(得分:2)

无需迭代一年中的所有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

答案 3 :(得分:2)

我根据上述答案提出的另一个选择。现在可以指定开始日期和结束日期。

#!/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

答案 4 :(得分:1)

您可以使用date获取当前周数。也许你可以对此进行排序:

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