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?

3 Answers 3

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.

2
  • Cool!: Vim is always a surprise to me! (+1)
    – JJoao
    Commented Oct 2, 2015 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
    Commented Oct 3, 2015 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}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.