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

查看:107
本文介绍了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天全站免登陆