Search code examples
sortingcommand-lineformatcut

how to format the output of a cat expression


I have a file in this format:

event: event1
event: event2
event: event2
event: event3

With this command:

cat event.txt |  cut -d : -f2 |sort |uniq -c |sort -n

I get this result:

1 event1
1 event3
2 event2

I would like to have instead an output like that:

event1 1
event2 2
event3 1

Do you have any idea of a way to do that?


Solution

  • If you want your output to be sorted by eventID like event[1] event[2] ... just take fedorqui's solution.

    If you want your output to keep the original order of col2 in input file:

    awk -F': *' 'NR==FNR{c[$2]++;next}$2 in c{print $2,c[$2];delete c[$2]}' file file
    

    an example:

    kent$  cat f
    event: event1
    event: event2
    event: event2
    event: event4
    event: event4
    event: event3
    
    kent$  awk -F': *' 'NR==FNR{c[$2]++;next}$2 in c{print $2,c[$2];delete c[$2]}' f f 
    event1 1
    event2 2
    event4 2
    event3 1