简体   繁体   English

解析日期并检查Bash中的日期是否最近

[英]Parsing date and checking how recent it is in Bash

I'm working on a Bash script (using Cygwin) that uses cURL to scrape a web page and check a certain date value. 我正在研究一个bash脚本(使用Cygwin),该脚本使用cURL刮取网页并检查某个日期值。 My cURL and grep calls result in the following line: 我的cURL和grep调用导致以下行:

<span style="float:right">Last Update: 9/30/2011 3:16:31 AM</span><p>

What I need to do with the date is check if it is within the last n days. 我需要处理的日期是检查它是否在最近的n天内。 What is the best way to approach this, and how should I parse the date? 解决此问题的最佳方法是什么?我应该如何解析日期?

Something like: 就像是:

DATESTRING="$(sed -e 's/.*Last Update: \([^<]*\)<.*/\1/' $MYINPUT)"
UPDATE=$(date -d "$DATESTRING" +%s) 
EPOCH=$(date -d "-$n days" +%s)
test "$UPDATE" -ge "$EPOCH" && echo "It's new!"

The 'date' program should be able to parse that date format. “日期”程序应该能够解析该日期格式。 For example: 例如:

% date -d '9/30/2011 3:16:31 AM'
Fri Sep 30 03:16:31 PDT 2011

So, you can use 'date' to convert that to something usable in bash (an integer, seconds since the epoch): 因此,您可以使用“日期”将其转换为可用的bash(整数,自纪元以来的秒数):

parseddate=$(something that extracts just the date from the line ...)
date -d "$parseddate" +%s

Then compare that to the result of 然后将其与

date -d '3 days ago' +%s

I would say that the absolute best way is to parse it with another language, for example Perl, since it will be easier to parse out the date. 我会说,绝对最佳的方法是用另一种语言(例如Perl)解析它,因为解析日期更容易。 If you'd rather stick with Bash, check the --date option in man date . 如果您愿意使用Bash,请检查man date--date选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM