At 1:06 AM

How to count characters, bytes and words in Vim

The article provides some information and tips on the subject: how to count characters, bytes and words in Vim.

Vim status line

When you do selection in vim in the status line there is information on how many chars/lines are selected:

  • when selection is in one line then you can see nr. of chars:

    -- visual --                                    34

  • when selection goes over several lines then you can see nr. of lines:

    -- visual --                                     2

Get me more information

I wanted to get information on how many chars are selected in selection over several lines. When I do selection and press the sequence (normal mode):

g+(CTRL+G)

reference :help v_g_CTRL-G

that gives me the information:

  • when there is no selection:

    col 34 of 60; line 193 of 216; word 927 of 1046; byte 7216 of 8226

  • when you select something:

    selected 1 of 216 lines; 4 of 1046 words; 45 of 8226 bytes

I want to count something special

Vim version 7 - adds option [n] to :s(ubstite) command:

[n] Report the number of matches, do not actually substitute. The [c] flag is ignored. The matches are reported as if ‘report’ is zero. Useful to |count-items|.

reference :help s_flags

This option can produce more power count functions, i.e. you can count number of matches of any regular expression. Examples:

:%s/.//gn - count all chars

5544 matches on 176 lines

:%s/\S//gn - count non-space chars

4080 matches on 167 lines

:%s/\s//gn - count space chars

1413 on 148 lines

Note

More information how to count items in vim can be found:

:help count-items

There you can find examples to count with :s command with [n] option, but there are mostly in the form:

   :%s/./&/gn

i.e. they use & as replacement char (replace the same). Since option [n] doesn’t replace anything the effect is the same as:

   :%s/.//gn

I tested in Vim version 7 and the behaviour is like described.

blog comments powered by Disqus

Notes

  1. trebor74hr posted this