简体   繁体   中英

Date Comparison in a format

I want to compare dates in a file in shell script with the below format with the current date and return some flag.

 Sep 15 2017 11:04AM

 Sep 16 2017 10:07AM

 Sep 19 2017 11:44AM

 Sep 20 2017 10:08AM

 Sep 21 2017 10:03AM

Awk scripting can be used here.

Assuming the file that contains the dates looks like this:

$ cat file1
Sep 15 2017 11:04AM
Sep 16 2017 10:07AM
Sep 19 2017 11:44AM
Sep 20 2017 10:08AM
Sep 21 2017 10:03AM
Oct 02 2017 10:03AM
Oct 05 2017 10:03AM
Oct 07 2017 10:03AM

Use this for GNU date

cat file1 | xargs -I@ bash -c " \
    seven_days_ago=$(date --date='7 days ago' +%s); \
    input=\$(date --date=\"@\" +%s); \
     if [ \"\$seven_days_ago\" -gt \"\$input\" ]; then \
        echo \"@\"; \
     fi;"

And this for BSD date

cat file1 | xargs -I@ bash -c " \
    seven_days_ago=$(date -v-7d +%s); \
    input=\$(date -j -f \"%b %d %Y %R%p\" \"@\" +%s); \
     if [ \"\$seven_days_ago\" -gt \"\$input\" ]; then \
        echo \"@\"; \
     fi;"

Output is the following. This dropped the date October 05 and 07 which are closer than 7 days.

Sep 15 2017 11:04AM
Sep 16 2017 10:07AM
Sep 19 2017 11:44AM
Sep 20 2017 10:08AM
Sep 21 2017 10:03AM
Oct 02 2017 10:03AM

How do you differentiate between GNU date and BSD date?

To check execute:

$ man date  | tail -n 1
GNU coreutils 8.22 

vs

$ man date | tail -n 1
BSD                             August 16, 2007                            BSD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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