bash - AWK matching values in a column and performing calculation -
i'm new @ awk , i'm trying figure out answer problem. have flat file following values:
403 | sanmateo | f | 2015-04-09 18:50:24.38 403 | sanmateo | t | 2015-04-09 18:45:24.36 403 | sanmateo | t | 2015-04-09 18:40:24.383 403 | sanmateo | f | 2015-04-09 18:35:24.357 403 | sanmateo | t | 2015-04-09 18:30:24.355 404 | redwoodcity| f | 2015-04-09 18:35:50.308 404 | redwoodcity| t | 2015-04-09 18:30:50.242 404 | redwoodcity| f | 2015-04-09 18:25:50.245 404 | redwoodcity| t | 2015-04-09 18:20:50.242 404 | redwoodcity| f | 2015-04-09 18:15:50.242
i want use awk compare $1 of current line $1 of next line, , $3 ~/f/. if statement true subtract $4 of next line $4 of current line , write difference in new column of current line , if false nothing. have far this:
awk 'begin {fs="|";} {if (nr $1 ~ nr++ $1 && $3 ~ /f/) subtract = nr $4 - nr++ $4; {print subtract}}' allhealthrecords_sorted
and that's not working. can please help?
save time_diff.awk
begin {fs = "[[:blank:]]*\\|[[:blank:]]*"} # convert "yyyy-mm-dd hh:mm:ss.fff" number function to_time(timestamp, fraction) { fraction = timestamp sub(/\..*$/, "", timestamp) gsub(/[-:]/, " ", timestamp) sub(/.*\./, "0.", fraction) return mktime(timestamp) + fraction } # gawk has no builtin abs() function function abs(val) { return( val < 0 ? -1*val : val) } # add time diff if condition met nr > 1 { diff = 0 if ($1+0 == key && flag == "f") diff = abs( to_time($4) - to_time(time) ) print line (diff > 0 ? " | " diff : "") } { # remember previous line's values key = $1+0; flag = $3; time = $4; line = $0 } end {print}
then
$ gawk -f time_diff.awk file 403 | sanmateo| f | 2015-04-09 18:50:24.38 | 300.02 403 | sanmateo| t | 2015-04-09 18:45:24.36 403 | sanmateo| t | 2015-04-09 18:40:24.383 403 | sanmateo| f | 2015-04-09 18:35:24.357 | 300.002 403 | sanmateo| t | 2015-04-09 18:30:24.355 404 | redwoodcity| f | 2015-04-09 18:35:50.308 | 300.066 404 | redwoodcity| t | 2015-04-09 18:30:50.242 404 | redwoodcity| f | 2015-04-09 18:25:50.245 | 300.003 404 | redwoodcity| t | 2015-04-09 18:20:50.242 404 | redwoodcity| f | 2015-04-09 18:15:50.242