ayda
ayda

Reputation: 21

dates calculation in bash

I have a file full of dates with this format (2002-09-26 02:20:30), I want to extract the last 5 days from the end of the file , here is what I wrote

 END-DATE=tail -1 my file (which is 2002-09-26 02:20:30)
 time=$(expr 60 * 60 * 24 * 5) ( counting 5days which is 432000) 
 up to know every thing is ok ! the problem is with next line, 
 START-DATE=`expr END-DATE - time`

seems it's wrong : expr: non-numeric argument

how should I convert this time to epoch time ?

Upvotes: 1

Views: 263

Answers (4)

hroptatyr
hroptatyr

Reputation: 4809

I've written a bunch of tools (dateutils) to tackle exactly these kinds of problems, in particular dgrep might help:

Off the cuff, I'd go for

EDATE=$(tail -n1 MY_FILE)
THRES=$(dadd "${EDATE}" -5d)
dgrep ">=${THRES}" < MY_FILE

Upvotes: 0

Jonathan Callen
Jonathan Callen

Reputation: 11561

If you just want the date 5 days before a given timestamp and have GNU Coreutils installed, you could use date -d "$(tail -n 1 some/file.ext) 5 days ago"; if you want that in a particular format, try looking at the man page date(1) (that is, enter man 1 date).

Upvotes: 1

nos
nos

Reputation: 229058

You need to refer to the variable, EDATE vs $EDATE (did you really mean END-DATE ?)

START_DATE=`expr $EDATE - time`

(Note that you cannot have a - in shell variable names, so START-DATE and END-DATE are invalid. Name them START_DATE and END_DATE rather)

Upvotes: 1

maialithar
maialithar

Reputation: 3123

EDATE is not defined, maybe you made a typo and it should be END-DATE?

Upvotes: 1

Related Questions