3

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
  • Have you tried the sort command? – jw013 Feb 10 '16 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 '16 at 19:50
  • 4
    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 '16 at 19:52
3
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.

3

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).

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.