如何使用bash中可用的工具生成范围内所有日期的列表? [英] How to generate a list of all dates in a range using the tools available in bash?

查看:47
本文介绍了如何使用bash中可用的工具生成范围内所有日期的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载一堆以ISO-8601日期命名的文件.有没有简单的方法可以使用bash + GNU coreutils来做到这一点?(或一些使wget/curl自动生成列表的技巧,但我发现不太可能)

I want to download a bunch of files named with ISO-8601 dates. Is there a simple way to do this using bash+GNU coreutils? (Or some trick to make wget/curl to generate the list automatically, but I find that unlikely)

类似于此问题,但不限于工作日:

Similar to this question, but not restricted to weekdays: How to generate a range of nonweekend dates using tools available in bash?. I guess that there is a simpler way to do it without that restriction.

还与>如何生成日期范围有关bash上的随机数据,但不限于一年.

推荐答案

如果您有GNU date ,则可以使用 for 循环

If you have GNU date, you could do use either a for loop in any POSIX-compliant shell:

# with "for"
for i in {1..5}; do 
    # ISO 8601 (e.g. 2020-02-20) using -I
    date -I -d "2014-06-28 +$i days"

    # custom format using +
    date +%Y/%m/%d -d "2014-06-28 +$i days"
done

until 循环,这一次使用Bash的扩展测试 [[:

or an until loop, this time using Bash's extended test [[:

# with "until"
d="2014-06-29"
until [[ $d > 2014-07-03 ]]; do 
    echo "$d"
    d=$(date -I -d "$d + 1 day")
done

请注意,如果您将条件更改为 ["$ d" \> ;,则 sh 的非古代版本也将进行词典编目比较.2014-07-03] .

Note that non-ancient versions of sh will also do lexicographical comparison if you change the condition to [ "$d" \> 2014-07-03 ].

这两个循环之一的输出:

Output from either of those loops:

2014-06-29
2014-06-30
2014-07-01
2014-07-02
2014-07-03

对于执行相同操作的更便携式方法,可以使用Perl脚本:

For a more portable way to do the same thing, you could use a Perl script:

use strict;
use warnings;
use Time::Piece;
use Time::Seconds;    
use File::Fetch;

my ($t, $end) = map { Time::Piece->strptime($_, "%Y-%m-%d") } @ARGV; 

while ($t <= $end) {
    my $url = "http://www.example.com/" . $t->strftime("%F") . ".log";
    my $ff = File::Fetch->new( uri => $url );
    my $where = $ff->fetch( to => '.' );  # download to current directory
    $t += ONE_DAY;
}

Time :: Piece,Time :: Seconds和File :: Fetch都是核心模块.像 perl wget.pl 2014-06-29 2014-07-03 一样使用它.

Time::Piece, Time::Seconds and File::Fetch are all core modules. Use it like perl wget.pl 2014-06-29 2014-07-03.

这篇关于如何使用bash中可用的工具生成范围内所有日期的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆