6

In vim, how can I count the number of characters on each line?

how
to
count
number
of characters?

For example, if I open a file with above text, I want to see counts like below

3
2
5
6
20
1
  • Is vim really a requirement here?
    – Paul
    Mar 8 '12 at 5:26
5

One way to do it:

:for i in range(1, line('$')) | echo i . ': ' . strlen(getline(i)) | endfor

This version shows the line number before the character count.

7

Another way:

:%!awk '{print length($0)}'

UPDATE: Even shorter (every keystroke counts!):

:%!awk '{print length}'

since I just now noticed that length defaults to entire line.

4
  • Seems to replace the current contents of vi. So you might potentially overwrite the original file contents. Mar 8 '12 at 13:11
  • 1
    @OliverSalzburg Then, do this: :%!tee >(awk '{print length($0)}'). This keeps the text.
    – new123456
    Mar 9 '12 at 1:09
  • Pro tip: If you want to sort by line length, change it to :%!awk '{print length " " $0}, then do :sort n
    – Cory Klein
    Jan 9 '13 at 17:51
  • Love this kind of answer. Pure and perfect vim.
    – digitai
    Jan 13 '16 at 16:08
1

The question was about vim, but just for comparison, here is how you can do that in Vedit:

Repeat(ALL) {
   EOL
   Num_Type(Cur_Col-1)
   Line(1, ERRBREAK)
}

or as one-liner:

Repeat(ALL){ EOL NT(CN-1) L(1, ERRBREAK) }

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.