Compare date via shell script

I have this text:

aaaaaaaaaaaaaaaaaaaaddddd
sadasdafnsdfoisjhpfnsf
dasnfdfmsdf until: Thu Apr 29 19:41:02 EEST 2021 dasd
asdasmda[mfiun[hg[sm df,
dfmsdf[ismdfsdfsd,flsdfsdf******************

I have to parse a date from a text and after that I have to compare it with today and if it greater to do something otherwise I have to do something else and I have to write it in shell script but I do not now it very well. Can someone give me a example how to do it.

Thanks in advance.

Answers


I would do it in two steps. (it could be done in one):

1, get the date string 2, do comparison

e.g.:

 kent$  d=$(echo "aaaaaaaaaaaaaaaaaaaaddddd
sadasdafnsdfoisjhpfnsf
dasnfdfmsdf until: Thu Apr 29 19:41:02 EEST 2021 dasd
asdasmda[mfiun[hg[sm df,
dfmsdf[ismdfsdfsd,flsdfsdf******************"|grep -o '[A-Z].*[0-9]')

check the var d:

kent$  echo $d
Thu Apr 29 19:41:02 EEST 2021

now we compare this date to today. we need convert both dates into seconds to do comparison:

kent$  echo $(($(date -d"${d}" +%s)-$(date +%s)))
251171977

I printed the result of above command out. In your case, you could just assign it to a var. or just check the result directly. if it >0 means the date in your text in future. otherwise, it is in the past(or same as today).

EDIT

some math:

with int:

kent$  echo $((251171977/(3600*24)))
2907

with precision:

kent$  echo "scale=2;251171977/(3600*24)"|bc 
2907.08

more precisely:

kent$  echo "scale=7;251171977/(3600*24)"|bc                                                                                                                                
2907.0830671

If possible, print the date in a form that is easier to parse. i.e.

`echo "the day of the year is `date '+%j'`"`

This makes comparisons much easier.


Need Your Help

How to sort Generic List Asc or Desc?

c# .net asp.net generics sorting

I have a generic collection of type MyImageClass, and MyImageClass has an boolean property "IsProfile". I want to sort this generic list which IsProfile == true stands at the start of the list.

Headless PDE build successful but no file

eclipse plugins ant pde

I've created a view plug-in for Eclipse. I can export the jar from the project and it's working quite good. I'm trying to create an Ant build script to automate it.