4

Say I do a regex search for a class of characters, e.g.:

/[clsktb]

Is there a way to either sort lines by the number of matched characters, or to show the number of matches next to the line numbers?

8

Here is a variation:

:%s/^/\=len(split(getline('.'), '[clsktb]\zs')).' '/

That searches for line start, and for each line, gets its content and checks how many matches it has and puts the result back on the line.

  • Cool!: Vim is always a surprise to me! (+1) – JJoao Oct 2 '15 at 20:37
  • The main strategy is the most important part of the answers. One minor thing: if I understand correctly, the result is correct if last char belongs to clsktb; otherwise is incremented by 1. – JJoao Oct 3 '15 at 10:13
2

If you must (using a Vim linked sausage command):

:sign unplace *
:g/^/ let n = 0 | let c = -1 | while c != 0 | let c = search('[-]', '', line('.')) | let n = n + 1 | endwhile | if n > 1 | exe 'sign define ' . n . ' text=' . (n-1) | exe 'sign place ' . n . ' line=' . line('.') . ' name=' . n . ' file=' . expand('%:p') | endif
1

Many Vims provide support for some scripting languages (Perl, Ruby, Python). If your vim has Perl support (some distributions don't provide it) you can use :perl perl-command and :perldo perl-command.

:perldo   $_ = y/clsktb// . " :: $_"

Perl's y/// returns the number of occurrences of the chars in the default string ($_). The new $_ is concatenation of that number followed by " :: " and the line.

\thanks{EvergreenTree}

  • 1
    Do note that this requires a vim build that has perl support enabled. – EvergreenTree Oct 5 '15 at 12:48
  • @EvergreenTree, thank you, I always forget to say that. – JJoao Oct 5 '15 at 13:24

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.