2

I have a file (test.csv) containing the following lines:

2016-08-23 00:00:00,270113184103681474

2016-08-23 00:00:00,270113184101689340

2016-08-23 00:00:00,270113184103681474

2016-08-23 00:00:00,270113184101689340

2016-08-23 01:00:00,270113184103681474

2016-08-23 01:00:00,270113184101689340

I would like to get the total number of lines and the unique occurrences of the 2nd column for each of the 1st columns. The desired output for the above lines would be:

2016-08-23 00:00:00, 4, 2

2016-08-23 01:00:00, 2, 2

Is there a simple grep/awk solution for this?

4

The naive solution is just to count each occurance and track to see if we've seen it before.

So:

awk -F, '{ t[$1]++; seen[$0]++; if (seen[$0] == 1) { u[$1]++ } }
         END { for (a in t) { print a "," t[a] "," u[a] } }'

The first line will keep track of total number of times the date has occured in t. It will track the number of times we seen each line in seen, and if this is the first time we've seen it then we know it's unique and count it in u.

The second line will iterate through the results and print them out.

1

If you have recourse to GNU awk

awk -F, '{a[$1]++; b[$1][$2]}; 
    END{for (k in a) printf "%s,%d,%d\n", k, a[k], length(b[k])}' test.csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.