Stryk9
Stryk9

Reputation: 39

BASH awk field separator to perform calculation

I basically have a text file containing data which consists of times in this format

(00:00)
(06:08)
(07:54)

I've done my share of research to determine how to take only specifically those times (filtering out all the other gunk), and even separating them using awk. The problem occurs when I attempt to add the digits. I seem to be getting a single digit 0 value...

My code is as follows:

cat somefile.txt | awk -F: '/([0-9][0-9]:[0-9][0-9])/{total+=$1}END{print total}'

Note: I am using brackets because the file contains other times, NOT enclosed in brackets... So i've attempted to get rid of the unwanted data, leaving me with only the above portions (00:00)

I'm trying to add the left portion together, which should obviously in this example result in a total of 13.

Really hope I can find a solution, and I'm sure it's something that is not exactly coming to my mind at the moment.

Upvotes: 0

Views: 94

Answers (1)

Kent
Kent

Reputation: 195049

try this line:

awk -F'[(:]' '{h+=$2}END{print h}' file

example:

kent$  echo "(00:00)
(06:08)
(07:54)"|awk -F'[(:]' '{h+=$2}END{print h}' 
13

EDIT

[(:] (I really want to type :) ) defines two FS (field separator)s ( or : so the line would be:

(06:08)
field 1 - ""
field 2 - 06
field 3 - 08)

if you want to get only minutes, you need to add ) to your FS too, otherwise you got $3 with the ending ).

Upvotes: 5

Related Questions