1

Sum of 2nd column based on 1st column(Hour value), i have a file 1st coumn is hour and 2nd coulmn is count. I'm calculating total based on the hour coulmn,

Input
01:01,15
01:02,16
01:03,6
02:01,44
02:02,33
02:05,22
14:01,55
14:02,06

Output:
01,37
02,99
14,61

I was able to create the required output by below steps.

create the unique hour file, below is sample code, while IFS=":" read f1 f2 do

if [ $f1 -eq 01 ]
then
echo $f1":",$f2 >> convertedFile01
fi

then from the converted file, I'm suming the column value. But this process generates 24 converted files, is there a way to generate the expected output in a simple way?

2 Answers 2

4

this one liner should do:

awk -F'[,:]' '{a[$1]+=$3}END{for(x in a)print x","a[x]}' file
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain
:( beat me to it. They are literally identical ha
2

save in array, print at end

awk -F'[:,]' '{a[$1]+=$3}END{for(i in a) print i","a[i]}' file

Explanation

 -F'[:,]' - Sets field separator to either a : or ,

  {a[$1]+=$3} - For each line store the value of the third field in an associative array 
                with the value in the first field as a key

  END{for(i in a) print i","a[i]} - At the end of the file, for each item in 
                         the array, print the key and the value for that key  

1 Comment

@EdMorton I know, he hadn't posted as i was writing :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.