How to reverse sort the output from grep -rc

8,034

Solution 1

You are almost there except you need the r modifier do a reverse sort:

grep -rc "Pattern" . | sort -t: -k2,2nr

check the r modifier after n.

Solution 2

You can use this,

~]# cat test
 data_x:12
 data_y:34
 data_z:56
 data_a:205
 data_b:1003

~]# sort -k2 -n -r -t: test
 data_b:1003
 data_a:205
 data_z:56
 data_y:34
 data_x:12

So for your code, you can do

~]# grep -rc "Pattern" . | sort -k2 -n -r -t:
Share:
8,034

Related videos on Youtube

tom
Author by

tom

Student at Southampton Uni studying Computer Science!

Updated on September 18, 2022

Comments

  • tom
    tom over 1 year

    I want to be able to sort the output from the grep -rc command,

    I am currently using the command:

    grep -rc "Pattern" . | sort -t: -rk2,2n
    

    however the list is still sorted from low to high, instead of high to low... it also prints out the exact output when using:

    grep -rc "Pattern" . | sort -t: -k2,2n
    

    So what I want is for the outputs:

    data_x:12 
    data_y:34
    data_z:56
    data_a:205
    data_b:1003
    

    to be sorted into

    data_b:1003
    data_a:205
    data_z:56
    data_y:34
    data_x:12
    
    • heemayl
      heemayl about 8 years
      Try grep -rc "Pattern" . | sort -t: -k2,2rn