LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Dates to epoch format (http://www.linuxquestions.org/questions/programming-9/dates-to-epoch-format-764551/)

sebelk 10-26-2009 10:12 AM

Dates to epoch format
 
Hi,

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:

Code:

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

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:
Code:

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:
Code:

#!/bin/bash

infile="$1"
outfile="${infile}.new"

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

Sample run:
Quote:

$ 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 infile.new
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

Code:

IFS="
"

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


All times are GMT -5. The time now is 03:02 AM.