Sort grep -c results

April 17th, 2007 toydi Posted in grep, sort, Text Manipulation | Hits: 67320 | 2 Comments »

grep -c "TODO:" *.c

foo.c:1
bar.c:0
spam.c:44
egg.c:32
matrix.c:0

grep -c displays the total count of matching lines for each input file, just like above.

Now, to sort the results by total count:

grep -c "TODO:" *.c | sort -nt: -k2

bar.c:0
matrix.c:0
foo.c:1
egg.c:32
spam.c:44

It sorts the list by total count or the 2nd field (-k2) by comparing them as numbers (-n). Don’t forget to set the field-separator as “:” (-t:).

Files with zero match does not need to be in the list. Here, I use one more grep to remove them, not very elegant though.

Anyone have a shorter way to complete the task?

grep -c "TODO:" *.c | grep -v ":0" | sort -t: -n -k2

2 Responses to “Sort grep -c results”

  1. I enjoyed your page. Keep up the good work! Feel free to visit my page. It\’s cool too.

  2. I’ll right away take hold off your rss as I can’t find
    your e-mail subscription hyperlink or newsletter service.
    Do you’ve any? Kindly permit me recognize so that I may
    just subscribe. Thanks.

    My web page :: conveyancing (Tracie)

Leave a Reply