Frage

I want to count the characters without whitespace of a visual selection. Intuitively, I tried the following

:'<,'>w !tr -d [:blank:] | wc -m

But vim does not like it.

War es hilfreich?

Lösung 3

You must escape special character for the shell, and use [:space:] better because it will delete also the newline character. It should be:

:'<,'>w !tr -d '[:space:]' | wc -m

Andere Tipps

This is possible with the following substitute command:

:'<,'>s/\%V\S//gn

The two magical ingredients are

  1. the n flag of the substitute command. What it does is

    Report the number of matches, do not actually substitute. (...) Useful to count items.

    See :h :s_flags, and check out :h count-items, too.

  2. the zero-width atom \%V. It matches only inside the Visual selection. As a zero-width match it makes an assertion about the following atom \S "non-space", which is to match only when inside the Visual selection. See :h /\%V.

The whole command thus substitutes :s nothing // for every non-whitespace character \S inside the Visual selection \%V, globally g – only that it doesn't actually carry out any substitutions but instead reports how many times it would have!

In order to count the non-whitespace characters within a visual selection in vim, you could do a

:'<,'>s/\S/&/g

Vim will then tell how many times it replaced non-whitespace characters (\S) with itself (&), that is without actually changing the buffer.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top