[ACCEPTED]-How to sort on column for rows containing a certain word-vim

Accepted answer
Score: 17

Pipe your input to an external command:

:%!grep sdf | sort -n -k3


  1. select the whole content using '%'
  2. pipe it to an external command using '!'
  3. grep onyl the lines containing 'sdf'
  4. sort these lines numerically (-n) on the third field (-k3)


Score: 8

2 vim commands:

:sort n /[^[:digit:]]*/
  • first deletes all lines that do not contain 'sdf'
  • second sorts numbers ignoring non-numbers


Score: 3

Maxim Kim has already given an excellent 11 answer and I was going to add this in a 10 comment, but it just got too complicated 9 so I'll stick it in an answer:

You could 8 simplify the pattern by using:

sort n /\D*/

as \D is equivalent 7 to [^[:digit:]] and is a lot less typing. For more 6 information, see

:help \D

To match on the third field 5 specifically, rather than just the first 4 digit, use

:sort n /\(\S\+\s+\)\{2}/`


:sort n /\v(\S+\s+){2}/


:help :sort
:help \S
:help \s
:help pattern.txt
:help \v

As an aside, some find it 3 easier to remember :g!/sdf/d, which does the same 2 as :v/sdf/d - :g! is the opposite of :g and is identical 1 to :v.

:help :v
:help :g
Score: 3

Sort by 2nd column by selecting it in visual 11 mode (e.g. Control+v), then run:


or to sort by 3rd 10 column

sort -k 3 


:sort /.*\%3v/

Alternatively select the lines you 9 wish to sort using the Shift+V command. Then enter

!sort -k 3n

or 8 use the below code to tell Vim to skip the 7 first two words in every line and sort on 6 whatever follows:

:%sort /^\S\+\s\+\S\+\s\+/ 

or i.e. sort by 8th line:

:sort /.*\%55v/

The 5 'virtual' specification is the absolute 4 number of column , which treats spaces + tabs 3 as single character (shortly, it doesn't 2 count tabs as eight spaces),

so to sort by 1 last column:

:%sort /\<\S\+\>$/ r

More Related questions