I know I can use wc
for counting characters, words and lines of files at the command line.
Is there any way I can can count the number of words while in vim?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityYou can count words and lines inside vi
using vi
's own counter:
Press g and then CTRL-g. Then the bottom line look for example like this:
Col 1 of 11; Line 1 of 106; Word 1 of 344; Byte 1 of 2644
Or use vi
's method to call shell commands:
:w !wc -w
This calls the save (:w
) command first and then wc -w
and shows the output. Example:
:w !wc -w
344
Press ENTER or type command to continue
Press Enter to go back to vi
.
:w !<cmd>
construct. It writes the current buffer to a pipe connected to the command. No separate write of the current buffer to a file is promised. Nevertheless, it does what question asked for.
vim
version 7.4.1042Since vim
version 7.4.1042, one can simply alter the statusline
as follows:
set statusline+=%{wordcount().words}\ words
set laststatus=2 " enables the statusline.
vim-airline
Word count is provided standard by vim-airline
for a number of file types, being at the time of writing:
asciidoc, help, mail, markdown, org, rst, tex ,text
If word count is not shown in the vim-airline
, more often this is due to an unrecognised file type. For example, at least for now, the compound file type markdown.pandoc
is not being recognised by vim-airline
for word count. This can easily be remedied by amending the .vimrc
as follows:
let g:airline#extensions#wordcount#filetypes = '\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'
set laststatus=2 " enables vim-airline.
The \v
statement overrides the default g:airline#extensions#wordcount#filetypes
variable. The last line ensures vim-airline
is enabled.
In case of doubt, the &filetype
of an opened file is returned upon issuing the following command:
:echo &filetype
Here is a meta-example:
You can also try for :!wc %
in Vim, though it counts the size of the file on-disk, not what is in Vim's buffer. This may or may not be what you wanted.
-w
flag to restrict the output to words only) to a delete answer from 2014 by D_Bye (who apparently self-deleted it).
For those who want to count number of words in a given piece of text (not whole file), use \S\+
regexp.
:s/\S\+//gn
Result. Vim will show you something like this: 10 matches on 1 line
When you hit :
in visual mode, vim prepends your command with '<,'>
which means to apply the command against the selected text.
\S\+
captures words, that is groups of characters separated by whitespace.
Plugins such as vim-airline can provide word counts for a file (and selections) as part of a status bar.