Count the number of occurrences of a word in a file in vim

May 29, 2013
:%s/./&/gn		characters
	:%s/\i\+/&/gn		words
	:%s/^//n		lines
	:%s/the/&/gn		"the" anywhere
	:%s/\<the\>/&/gn	"the" as a word
Advertisements

How to set up autoindent “gg=G” automatically before any file is opened in Vim

May 7, 2013
  • Vim events : 
  • Vim autocommands : http://vimdoc.sourceforge.net/htmldoc/autocmd.html
  • :autocmd BufRead * :normal gg=G

Substitute (Search and replace) command in the vi editor

June 5, 2012

1. How to replace an occurrence of “old_string” by “new_string” in a file

{code} :s/old_string/new_string/g{/code}

2. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines 1 to 10

:1,10s/old_string/new_string/g
3. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines 1 to the current line ?

The current line (where the cursor is located) can be specified as a single dot (.).

:1,.s/old_string/new_string/g

4. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines from the current line to the last line?

The last line can be specified as a dollar sign ($).

:.,$s/old_string/new_string/g

5. How do you search the whole file ?

:%s/old_string/new_string/g or
:1,$s/old_string/new_string/g
6. How can you execute a search and replace on the current line and the next five lines ?

The beginning or ending line for a range may be given as a positive or negative number of lines offset from the current line.

:.,+5s/old_string/new_string/g

7. How can you execute a search and replace from five lines above the current line through the current line ?

:-5,.s/old_string/new_string/g

8. How can you perform a search and replace from five lines above the current line through five lines below the current line ?

:-5,+5s/old_string/new_string/g