Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the output obtained with grep -c?

Tags:

grep

sorting

I use the following 'grep' command to get the count of the string alert in each of my files at the given path:

grep 'alert' -F /usr/local/snort/rules/* -c

How do I sort the resulting output in desired order- say ascending order, descending order, ordered by name, etc. An answer specific to these cases is sufficient.

You may freely suggest a command other than grep as well.

like image 335
pnp Avatar asked Sep 04 '12 08:09

pnp


People also ask

How do I sort grep results?

To sort anything you need to use the sort command. You can use grep to identify the lines to sort, then pipe the output to sort and use the -h switch for a numeric sort with -k identifying what column to sort on.

How do I print grep output?

The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do you get 5 lines before and after grep?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do I search for a phrase using grep?

To use grep to search for words in a file, type grep, the word or words you want to search for, the files you want to look in, and press <Enter>. If you want to look for more than one word, you need to put ``double quotes'' around the words.


1 Answers

Pipe it into sort. Assuming your filenames have no colons, use the "-t" option to specify the colon as field saparator. Use -n for numerical sorting.

Example:

grep 'alert' -F /usr/local/snort/rules/* -c | sort -t: -n -k2

should split lines into fields separated by ":", use the second field for sorting, and treat this as numbers (so 21 is actually later than 3).

like image 187
Christian Stieber Avatar answered Nov 16 '22 02:11

Christian Stieber