0

I have a flat file with data in the following format

(1+01:01)
(06:18)
(00:02)

I can use awk to sum up the data if it's in the form of seconds like so

16
32
64

cat file | awk '{SUM+=$1} END {print SUM}'

Is there a way I can convert the values stored in the flat file to seconds?

user784637
  • 15,392
  • 32
  • 93
  • 156
  • Can you give a sample `date` command to convert `1+01:01` to seconds? – user784637 Feb 22 '13 at 07:29
  • 1
    `gawk` has [date/time functions](http://www.gnu.org/software/gawk/manual/html_node/Time-Functions.html) which may be of interest to you. If you just want to calculate seconds, why don't you just multiply it out. Exactly what is your expected output? What is `1+01:01`? – Steve Feb 22 '13 at 07:30
  • I can multiply it out, I was just wondering if there were any built in tools to do it =) – user784637 Feb 22 '13 at 07:31

2 Answers2

2

GNU date is pretty good at parsing dates, but 1+01:01 is not supported. You could still use it if you let sed modify the input a little bit, and assuming it means 1 hour + 1 hour + 1 minute.

Here's is one way you could parse the file with GNU grep, sed and date:

<infile grep -o '[^()]*' | 
sed 's/^([0-9]+)[+-]/\1 hour /; 
     s/^/date -d "/; 
     s/$/ 1970-01-01 UTC" +%s/e'

Output:

7260
22680
120

Leave of the e flag to see what commands sed is executing.

Thor
  • 45,082
  • 11
  • 119
  • 130
1

Why not use awk for this as well? Check out this stackoverflow answer: Simple way to convert HH:MM:SS (hours:minutes:seconds.split seconds) to seconds

Community
  • 1
  • 1
Max
  • 11
  • 4