Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
    
Is vim really a requirement here? – Paul Mar 8 '12 at 5:26
up vote 4 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
    
Seems to replace the current contents of vi. So you might potentially overwrite the original file contents. – Oliver Salzburg 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. – datelligence Jan 13 at 16:08

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) }
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .