Vim Tips Wiki

Sorting lines in a file based on the number of words in each line

Redirected from VimTip800

1,624pages on
this wiki
Add New Page
Talk0 Share
Tip 800 Printable Monobook Previous Next

created 2004 · complexity intermediate · version 6.0

Here is one use of substitute with an expression (:help sub-replace-expression).

I needed to sort a file according to the number of words in each line. Using the :s command, I inserted the number of words each line contains, at the beginning of the line.

To simplify sorting (using the excellent VisSort), instead of inserting a number, I put the corresponding character (number plus 64, so a line with one word will start with 'A').

Here is the expression I used:

:%s/^.*/\=nr2char(strlen((substitute(substitute(submatch(0), "\\S\\+", "x", "g"), "\\s","","g")))+64) . "\t" . submatch(0)

Explanation, from the inside out:

Replace all consecutive non space by a single x (each word is now a single x):

part1 = substitute(submatch(0), "\\S\\+", "x", "g")

Remove the spaces between "x":

part2 = substitute(part1,"\\s","","g")

Count the number of "x":

part3 = strlen(part2)

Get the ASCII char representing the number of words + 64:

part4 = nr2char(part3+64)

I replace all lines (^.*) by that ASCII char, followed by a tab and the initial line itself.

I can then sort, then remove all characters between the beginning of lines and the first tab.


To sort all file:


To remove prefix of letter and tab:


Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.