-   Programming (
-   -   Dates to epoch format (

sebelk 10-26-2009 10:12 AM

Dates to epoch format

I have a file with a lot of lines as you see below:

Wed Jun 24 10:41:31 2009 [johndoe]
Tue May 24 10:43:31 2009 [maryblack]

I'd want to convert dates to epoch but I don't know how to do it through all file.

I know that I can change to epoch using:
date -d 'Tue May 19 15:22:49 2009' +%s

Perhaps it sounds stupid but I don't know how to do it. Could you help me?

Thanks in advance!!

sploot 10-26-2009 10:38 AM

If they are all dated 2009, and you dont have any names that follow that include 2009, then this should work:


for i in $(cat $file); do
  date -d "`echo $i|sed -e 's/\(.*2009\) /\1/'`" +%s

But this is only going to put it on the stout, if you want to do anything with this data, like store it in a file, then add a pipe to the end of the date line: >> $outputfile

Good luck!

EDIT: This is also assuming that the file ONLY contains the date lines. If there are other lines that need to be cleaned out first, then change the for line to this:

for i in $(cat $file|grep 2009); do

druuna 10-26-2009 11:24 AM

@sploot: Did you try your solution?

The reason it doesn't work are the spaces in the input.

This should work:



cat $infile | \
while read oneLine
  datePart="${oneLine% *}"
  restPart="${oneLine##* }"
  newDatePart="`date -d "${datePart}" +%s`"
  echo "${datePart} - ${restPart} - ${newDatePart}"
  echo "${newDatePart} ${restPart}" >> outfile

Sample run:

$ cat infile
Wed Jun 24 10:41:31 2009 [johndoe]
Tue May 24 10:43:31 2009 [maryblack]

$ ./toEpoch infile
Wed Jun 24 10:41:31 2009 - [johndoe] - 1245832891
Tue May 24 10:43:31 2009 - [maryblack] - 1243154611

$ cat
1245832891 [johndoe]
1243154611 [maryblack]
You probably want to remove the first echo line, it is just there to show what the variables hold.

Safe the file as toEpoch (or something you like), give it execute permissions (chmod 750 toEpoch). The outfile will have the name of the infile with ".new" added.

Hope this helps.

sploot 10-26-2009 02:50 PM

Oops. Sorry, if you include



then it should work. I thought I had that in there.

All times are GMT -5. The time now is 11:49 PM.