我需要在linux中获取给定日期范围内所有星期六的列表,例如:20170101到20170630,格式为YYYYMMDD
答案1
使用 GNU 日期和暴力破解:
start=20170101
end=20170630
cur=$start
increment="1 day"
while [ $(date +%s -d "$cur") -le $(date +%s -d "$end") ]
do
if [ "$(date +%A -d "$cur")" = "Saturday" ]
then
printf "%s\n" "$cur"
increment="1 week"
fi
cur=$(date +%Y%m%d -d "$cur + $increment")
done
答案2
用这个制作一个脚本:
#! /bin/bash
cur=20170101
end=20170630
# First upcoming saturday is:
cur=$(( cur+(6-$( date -d $cur +%w )) ))
# Keep increment by 7 days until 'end'
while (( end>cur )); do
echo $cur
cur=$( date -d "$cur+7days" +%Y%m%d )
done
它将给出:
$ ./ILoveSaturdays.bash
20170107
20170114
...
20170617
20170624
答案3
使用 GNU date
,尝试运行date
尽可能少的命令 (2):
TZ=UTC0 date -f - '+%s %w' << EOF |
20170101
20170630
EOF
awk -v d=86400 '{
d1 = $1 + (6 - $2) * d
getline
for (t = d1; t <= $1; t += 7 * d) print "@" t}' |
TZ=UTC0 date -f - +%Y%m%d
答案4
让我们在 perl 中执行此操作:
perl -e '
use POSIX "strftime";
$start=$ARGV[0];
$end=$ARGV[1];
if(! ($start =~ /^(\d\d\d\d)(\d\d)(\d\d)$/)){
die "bad format for first arg";
}
$epoch=(($1-1970)*365+($2-1)*28+$3-1)*24*60*60;
if(! ($end =~ /^(\d\d\d\d)(\d\d)(\d\d)$/)){
die "bad format for first arg";
}
while(1){
$cur=strftime("%Y%m%d", gmtime $epoch);
if($cur ge $start){last;};
$epoch += 24*60*60;
}
while(1){
$wd = strftime("%u", gmtime $epoch);
$cur = strftime("%Y%m%d", gmtime $epoch);
if($cur >= $end){last;}
if($wd == 6){
printf "$cur\n";
}
$epoch += 24*60*60;
}' 20170101 20170630