bash 如何在shell脚本中以%Y%m%d格式打印两个日期之间的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37220644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print dates between two dates in format %Y%m%d in shell script?
提问by buzzinolops
I have two arguments as inputs: startdate=20160512
and enddate=20160514
.
我有两个参数作为输入: startdate=20160512
和enddate=20160514
。
I want to be able to generate the days between those two dates in my bash script, not including the startdate, but including the enddate:
我希望能够在我的 bash 脚本中生成这两个日期之间的天数,不包括开始日期,但包括结束日期:
20160513 20160514 I am using linux machine. How do I accomplish this? Thanks.
20160513 20160514 我使用的是 linux 机器。我该如何实现?谢谢。
回答by John1024
Using GNU date:
使用 GNU 日期:
$ d=; n=0; until [ "$d" = "$enddate" ]; do ((n++)); d=$(date -d "$startdate + $n days" +%Y%m%d); echo $d; done
20160513
20160514
Or, spread over multiple lines:
或者,分布在多行上:
startdate=20160512
enddate=20160514
d=
n=0
until [ "$d" = "$enddate" ]
do
((n++))
d=$(date -d "$startdate + $n days" +%Y%m%d)
echo $d
done
How it works
这个怎么运作
d=; n=0
Initialize variables.
until [ "$d" = "$enddate" ]; do
Start a loop that ends on
enddate
.((n++))
Increment the day counter.
d=$(date -d "$startdate + $n days" +%Y%m%d)
Compute the date for
n
days afterstartdate
.echo $d
Display the date.
done
Signal the end of the loop.
d=; n=0
初始化变量。
until [ "$d" = "$enddate" ]; do
开始一个以 结束的循环
enddate
。((n++))
增加日计数器。
d=$(date -d "$startdate + $n days" +%Y%m%d)
计算
n
之后天的日期startdate
。echo $d
显示日期。
done
发出循环结束的信号。
回答by Sanjeev
This should work on OSX, make sure your startdate is lesser than enddate, other wise try with epoch.
这应该适用于 OSX,确保您的开始日期小于结束日期,否则请尝试使用 epoch。
startdate=20160512
enddate=20160514
loop_date=$startdate
let j=0
while [ "$loop_date" -ne "$enddate" ]; do
loop_date=`date -j -v+${j}d -f "%Y%m%d" "$startdate" +"%Y%m%d"`
echo $loop_date
let j=j+1
done
回答by nisetama
Another option is to use dateseq
from dateutils
(http://www.fresse.org/dateutils/#dateseq). -i
changes the input format and -f
changes the output format.
另一种选择是使用dateseq
from dateutils
( http://www.fresse.org/dateutils/#dateseq)。-i
更改输入格式并-f
更改输出格式。
$ dateseq -i%Y%m%d -f%Y%m%d 20160512 20160514
20160512
20160513
20160514
$ dateseq 2016-05-12 2016-05-14
2016-05-12
2016-05-13
2016-05-14