Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So so far, the code looks like this:

grep -rc 'Author' $1

It prints out all the files in the directory, which is taken as an argument. However, how would I sort the output (for example):

 - data1:43 
 - data2:56
 - data3:14

into a high to low list:

 - data2:56
 - data1:43
 - data3:14
share|improve this question
Have you tried the sort command? – jw013 Feb 10 at 19:49
Yes but it sorts the file name, not the count of how many times Author is in the file – tom Feb 10 at 19:50
Sort does more things than you might be aware of, which you can learn more about by reading the man page. Try sort -t : -k 2,2n – jw013 Feb 10 at 19:52
Thanks for your help, I will look at the man page – tom Feb 10 at 19:57
Keep in mind that -c counts the no. of matching lines not "how many times Author is in the file" – don_crissti Feb 10 at 20:04
grep -rc 'Author' $1 | sort -t : -k 2,2n

is good if you want the number of lines containing the keyword, regardless how many times it repeats on any given line. If you want the actual word count, you should use this

echo $1:$(grep -o 'Author' $1|wc -l) | sort -t : -k 2,2n

-o option for grep is most probably available on the gnu version of grep. If you are using grep, provided by an older, legacy system, it might not be available. Just a quick heads up.

share|improve this answer

To sort from highest to lowest:

grep -rc 'Author' $1 | sort -r -t ':' -k2,2n
  • -r sorts in reverse order, that is, from highest to lowest.
  • -t introduces the separator.
  • -k introduces which fields to sort by. The fields are separated by the separator defined by -t. This syntax means to sort by all of the fields between 2 and 2 (so just the second field). The n means to use numerical values rather than lexicographic order (so that e.g. 10 goes after 9, not just after 1).
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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