我对Linux不熟悉。如何在给定日期范围内打印和存储日期。
例如,假设startdate=2013-03-01并且enddate=2013-03-25;我想打印出该范围内的所有日期。
提前感谢。
date
执行日历算术:startdate=2013-03-15
enddate=2013-04-14
curr="$startdate"
while true; do
echo "$curr"
[ "$curr" \< "$enddate" ] || break
curr=$( date +%Y-%m-%d --date "$curr +1 day" )
done
使用 [ ... ]
时,您需要转义 <
来避免与输入重定向运算符混淆。
如果开始日期大于结束日期,则会出现打印开始日期的问题。
echo {100..1} | xargs -I{} -d ' ' date --date={}' days ago' +"%Y-%m-%d"
$ startdate='2016-03-01'; echo {0..10} | xargs -I{} -d ' ' date --date="$startdate +"{}" days" +"%Y-%m-%d"
2016-03-01
2016-03-02
2016-03-03
....
- user5672998另一个选项是使用来自dateutils
(http://www.fresse.org/dateutils/#dateseq)的dateseq
:
$ dateseq 2013-03-01 2013-03-25
2013-03-01
2013-03-02
2013-03-03
2013-03-04
2013-03-05
2013-03-06
2013-03-07
2013-03-08
2013-03-09
2013-03-10
2013-03-11
2013-03-12
2013-03-13
2013-03-14
2013-03-15
2013-03-16
2013-03-17
2013-03-18
2013-03-19
2013-03-20
2013-03-21
2013-03-22
2013-03-23
2013-03-24
2013-03-25
:read ! dateseq 2018-12-04 2019-12-31
。:read
将输出附加到当前缓冲区(文件);!
执行外部(BASH)命令(dateseq ...
)。 - Victoria Stuartdate
将日期转换为秒,进行一些数学运算后再将其转换回去即可:#/bin/bash
dstart=2013-03-01
dend=2013-03-25
# convert in seconds sinch the epoch:
start=$(date -d$dstart +%s)
end=$(date -d$dend +%s)
cur=$start
while [ $cur -le $end ]; do
# convert seconds to date:
date -d@$cur +%Y-%m-%d
let cur+=24*60*60
done
更多关于日期参数的信息,请参阅man date
。
#!/bin/bash
startdate=2013-03-15
enddate=2013-04-14
curr="$startdate"
while true; do
[ "$curr" \< "$enddate" ] || { echo "$curr"; break; }
echo "$curr"
curr=$( date +%Y-%m-%d --date "$curr +1 day" )
done
一行版本:
seq 0 24 | xargs -I {} date +"%Y-%m-%d" -d '20130301 {}day'
# this version is ok if the dates not cross next month
seq -f'%.f' 20130301 20130325
start_date="20191021"
end_date="20191025"
dates=()
while [[ "${start_date}" != "${end_date}" ]];do
formatted_date=$(date -d "${start_date}" +"%Y%m%d")
dates+=( "${formatted_date}" )
start_date=$(date -d "$start_date +1 day" +"%Y%m%d")
done
echo "$curr"
。date --date "$curr +1 day"
比let cur=..
更好。 - xtof pernod