Bash 脚本比较两个日期变量 [英] Bash script compare two date variables

查看:30
本文介绍了Bash 脚本比较两个日期变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户提供的日期与文件中的日期进行比较,基本上是一个列出了大量日期和时间的文本文件.

I'm trying to compare a date given by a user to a date in a file, basically a text file with lots of dates and times listed.

例如,用户会输入一个日期,例如 22/08/2007 和 1:00 的时间,我需要脚本做的是计算文本文件中在用户提供的日期之后有多少个日期.

for example the user would enter a date such as 22/08/2007 and a time of 1:00, what i need the script to do is count how many dates in the text file are after the date given by the user.

我设法通过将文本文件中的每个日期转换为 unix 时间戳,然后比较两者来实现这一点.有没有办法在 bash 中简单地比较两个日期?

I’ve managed to accomplish this by converting each date in the text file to unix timestamp and then comparing the two. Is there no way of simply comparing two dates in bash?

提前致谢

推荐答案

GNU date 命令可以将日期转换为自 1970 年以来的秒数.试试这个脚本:

The GNU date command can convert a date into the number of seconds since 1970. Try this script:

#! /bin/bash
DATE=$(date -d "$3-$2-$1 01" '+%s')
COUNT=0
tr '/' ' ' | {
    while read D M Y ; do
    THIS=$(date -d "$Y-$M-$D 01" '+%s')
    if (( THIS > DATE )) ; then
        COUNT=$((COUNT + 1))
    fi
    done
    echo $COUNT
}

它需要三个参数和标准输入中的原始日期:

It expects three arguments and the raw dates in stdin:

for D in $(seq 19 25) ; do echo $D/08/2007 ; done | ./count.sh 22 08 2007
3

它会一直工作到 2038 年.;-)

It will work till 2038. ;-)

这篇关于Bash 脚本比较两个日期变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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