Vim replace word all

Vim provides the :s (substitute) command for search and replace; this tip shows examples of how to substitute. On some systems, gvim has Find and Replace on the Edit menu (:help :promptrepl), however it is easier to use the :s command due to its command line history and ability to insert text (for example, the word under the cursor) into the search or replace fields.

The :substitute command searches for a text pattern, and replaces it with a text string. There are many options, but these are what you probably want:

:s/foo/bar/g
Find each occurrence of ‘foo’ (in the current line only), and replace it with ‘bar’.
:%s/foo/bar/g
Find each occurrence of ‘foo’ (in all lines), and replace it with ‘bar’.
:%s/foo/bar/gc
Change each ‘foo’ to ‘bar’, but ask for confirmation first.
:%s/<foo>/bar/gc
Change only whole words exactly matching ‘foo’ to ‘bar’; ask for confirmation.
:%s/foo/bar/gci
Change each ‘foo’ (case insensitive due to the i flag) to ‘bar’; ask for confirmation.
:%s/fooc/bar/gc is the same because c makes the search case insensitive.
This may be wanted after using :set noignorecase to make searches case sensitive (the default).
:%s/foo/bar/gcI
Change each ‘foo’ (case sensitive due to the I flag) to ‘bar’; ask for confirmation.
:%s/fooC/bar/gc is the same because C makes the search case sensitive.
This may be wanted after using :set ignorecase to make searches case insensitive.

The g flag means global – each occurrence in the line is changed, rather than just the first. This tip assumes the default setting for the 'gdefault' and 'edcompatible' option (off), which requires that the g flag be included in %s///g to perform a global substitute. Using :set gdefault creates confusion because then %s/// is global, whereas %s///g is not (that is, g reverses its meaning).

When using the c flag, you need to confirm for each match what to do. Vim will output something like:
replace with foobar (y/n/a/q/l/^E/^Y)?
(where foobar is the replacement part of the :s/.../.../ command). You can type y which means to substitute this match, n to skip this match, a to substitute this and all remaining matches («all» remaining matches), q to quit the command, l to substitute this match and quit (think of «last»), ^E to scroll the screen up by holding the Ctrl key and pressing E and ^Y to scroll the screen down by holding the Ctrl key and pressing Y. However, the last two choices are only available, if your Vim is a normal, big or huge built or the insert_expand feature was enabled at compile time (look for +insert_expand in the output of :version).

Also when using the c flag, Vim will jump to the first match it finds starting from the top of the buffer and prompt you for confirmation to perform replacement on that match. Vim applies the IncSearch highlight group to the matched text to give you a visual cue as to which match it is operating on (set to reverse by default for all three term types as of Vim 7.3). Additionally, if more than one match is found and you have search highlighting enabled with :set hlsearch, Vim highlights the remaining matches with the Search highlight group. If you do use search highlighting, you should make sure that these two highlight groups are visually distinct or you won’t be able to easily tell which match Vim is prompting you to substitute.

Details[]

Search range:

:s/foo/bar/g Change each ‘foo’ to ‘bar’ in the current line.
:%s/foo/bar/g Change each ‘foo’ to ‘bar’ in all the lines.
:5,12s/foo/bar/g Change each ‘foo’ to ‘bar’ for all lines from line 5 to line 12 (inclusive).
:'a,'bs/foo/bar/g Change each ‘foo’ to ‘bar’ for all lines from mark a to mark b inclusive (see Note below).
:'<,'>s/foo/bar/g When compiled with +visual, change each ‘foo’ to ‘bar’ for all lines within a visual selection. Vim automatically appends the visual selection range (‘<,’>) for any ex command when you select an area and enter :. Also, see Note below.
:.,$s/foo/bar/g Change each ‘foo’ to ‘bar’ for all lines from the current line (.) to the last line ($) inclusive.
:.,+2s/foo/bar/g Change each ‘foo’ to ‘bar’ for the current line (.) and the two next lines (+2).
:g/^baz/s/foo/bar/g Change each ‘foo’ to ‘bar’ in each line starting with ‘baz’.
Note: As of Vim 7.3, substitutions applied to a range defined by marks or a visual selection (which uses a special type of marks ‘< and ‘>) are not bounded by the column position of the marks by default. Instead, Vim applies the substitution to the entire line on which each mark appears unless the %V atom is used in the pattern like: :'<,'>s/%Vfoo/bar/g.

When searching:

., *, , [, ^, and $ are metacharacters.
+, ?, |, &, {, (, and ) must be escaped to use their special function.
/ is / (use backslash + forward slash to search for forward slash)
t is tab, s is whitespace (space or tab)
n is newline, r is CR (carriage return = Ctrl-M = ^M)
After an opening [, everything until the next closing ] specifies a /collection. Character ranges can be represented with a -; for example a letter a, b, c, or the number 1 can be matched with [1a-c]. Negate the collection with [^ instead of [; for example [^1a-c] matches any character except a, b, c, or 1.
{#} is used for repetition. /foo.{2} will match foo and the two following characters. The is not required on the closing } so /foo.{2} will do the same thing.
(foo) makes a backreference to foo. Parenthesis without escapes are literally matched. Here the is required for the closing ).

When replacing:

r is newline, n is a null byte (0x00).
& is ampersand (& is the text that matches the search pattern).
inserts the text matched by the entire pattern
1 inserts the text of the first backreference. 2 inserts the second backreference, and so on.

You can use other delimiters with substitute:

:s#http://www.example.com/index.html#http://example.com/#

Save typing by using zs and ze to set the start and end of a pattern. For example, instead of:

:s/Copyright 2007 All Rights Reserved/Copyright 2008 All Rights Reserved/

Use:

:s/Copyright zs2007ze All Rights Reserved/2008/

Using the current word or registers[]

:%s//bar/g
Replace each match of the last search pattern with ‘bar’.
For example, you might first place the cursor on the word foo then press * to search for that word.
The above substitute would then change all words exactly matching ‘foo’ to ‘bar’.
:%s/foo/<c-r><c-w>/g
Replace each occurrence of ‘foo’ with the word under the cursor.
<c-r><c-w> means that you press Ctrl-R then Ctrl-W.
The word under the cursor will be inserted as though you typed it.
:%s/foo/<c-r><c-a>/g
Replace each occurrence of ‘foo’ with the WORD under the cursor (delimited by whitespace).
<c-r><c-a> means that you press Ctrl-R then Ctrl-A.
The WORD under the cursor will be inserted as though you typed it.
:%s/foo/<c-r>a/g
Replace each occurrence of ‘foo’ with the contents of register ‘a’.
<c-r>a means that you press Ctrl-R then a.
The contents of register ‘a’ will be inserted as though you typed it.
:%s/foo/<c-r>0/g
Same as above, using register 0 which contains the text from the most recent yank command. Examples of yank (copy) commands are yi( which copies the text inside parentheses around the cursor, and y$ which copies the text from the cursor to the end of the line. After a yank command which did not specify a destination register, the copied text can be entered by pressing Ctrl-R then 0.
:%s/foo/=@a/g
Replace each occurrence of ‘foo’ with the contents of register ‘a’.
=@a is a reference to register ‘a’.
The contents of register ‘a’ is not shown in the command. This is useful if the register contains many lines of text.
:%s//<c-r>//g
Replace each match of the last search pattern with the / register (the last search pattern).
After pressing Ctrl-R then / to insert the last search pattern (and before pressing Enter to perform the command), you could edit the text to make any required change.
:%s/<c-r>*/bar/g
Replace all occurrences of the text in the system clipboard (in the * register) with ‘bar’ (see next example if multiline).
On some systems, selecting text (in Vim or another application) is all that is required to place that text in the * register.
:%s/<c-r>a/bar/g
Replace all occurrences of the text in register ‘a’ with ‘bar’.
<c-r>a means that you press Ctrl-R then a. The contents of register ‘a’ will be inserted as though you typed it.
Any newlines in register ‘a’ are inserted as ^M and are not found.
The search works if each ^M is manually replaced with ‘n’ (two characters: backslash, ‘n’).
This replacement can be performed while you type the command:

:%s/<c-r>=substitute(@a,"n",'\n','g')<CR>/bar/g
The "n" (double quotes) represents the single character newline; the '\n' (single quotes) represents two backslashes followed by ‘n‘.
The substitute() function is evaluated by the <c-r>= (Ctrl-R =) expression register; it replaces each newline with a single backslash followed by ‘n‘.
The <CR> indicates that you press Enter to finish the = expression.
:%s/<c-r>0/bar/g
Same as above, using register 0 which contains the text from the most recent yank command.

See Paste registers in search or colon commands instead of using the clipboard.

Additional examples[]

:%s/foo/bar/
On each line, replace the first occurrence of «foo» with «bar».
:%s/.*zsfoo/bar/
On each line, replace the last occurrence of «foo» with «bar».
:%s/<foo>//g
On each line, delete all occurrences of the whole word «foo».
:%s/<foo>.*//
On each line, delete the whole word «foo» and all following text (to end of line).
:%s/<foo>.{5}//
On each line, delete the first occurrence of the whole word «foo» and the following five characters.
:%s/<foo>zs.*//
On each line, delete all text following the whole word «foo» (to end of line).
:%s/.*<foo>//
On each line, delete the whole word «foo» and all preceding text (from beginning of line).
:%s/.*ze<foo>//
On each line, delete all the text preceding the whole word «foo» (from beginning of line).
:%s/.*(<foo>).*/1/
On each line, delete all the text preceding and following the whole word «foo».
:%s/<foo(bar)@!/toto/g
On each line, replace each occurrence of «foo» (which starts a word and is not followed by «bar») by «toto».
:s/^(w)/u1/
If the first character at the beginning of the current line only is lowercase, switch it to uppercase using u (see switching case of characters).
:%s/(.*n){5}/&r/
Insert a blank line every 5 lines.
The pattern searches for (.*n) (any line including its line ending) repeated five times ({5}).
The replacement is & (the text that was found), followed by r (newline).
:%s/<foo(a*)>/=len(add(list, submatch(1)))?submatch(0):submatch(0)/g
Get a list of search results. (the list must exist)
Sets the modified flag, because of the replacement, but the content is unchanged.
Note: With a recent enough Vim (version 7.3.627 or higher), you can simplify this to:
:%s/<foo(a*)>/=add(list, submatch(1))/gn
This has the advantage, that the buffer won’t be marked modified and no extra undo state is created. The expression in the replacement part is executed in the sandbox and not allowed to modify the buffer.

Special cases[]

For substituting patterns with corresponding case-sensitive text, Michael Geddes’s keepcase plugin can be used, e.g.:

:%SubstituteCase/cHello/goodBye/g
Substitute ‘Hello hello helLo HELLO’ by ‘Goodbye goodbye goodBye GOODBYE’

For changing the offsets in a patch file (line number of a block), this little snippet can be used:

s/^@@ -(d+),(d+) +(d+),(d+) @@$/="@@ -".eval(submatch(1)+offsetdiff).",".submatch(2)." +".eval(submatch(3)+offsetdiff).",".submatch(4)." @@"/g

Useful when we want to strip some blocks from a patch, without patch having to complain about offset differences.

Note Should try to make the expression more compact, but don’t know how without having the possibility of modifying unwanted lines.

Change and repeat[]

  1. Search for text using / or for a word using *.
  2. In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish.
  3. From normal mode, search for the next occurrence that you want to replace (n) and press . to repeat the last change.

See also: using substitute[]

  • 63 Applying substitutes to a visual block
  • 81 Substitute characters and lines easily
  • 159 Keystroke Saving Substituting and Searching
  • 406 Alternate delimiters for the replace command
  • 438 Search and replace in a visual selection
  • 464 Search and replace the word under the cursor
  • 479 Replace with no typing
  • 573 Repeating a substitute from current cursor position
  • 605 Replace a word with the yanked text
  • 654 Special characters in the substitute command
  • 755 Using an expression in substitute command
  • 808 Replace a visual-block of text with another such block
  • 915 Using g instead of substitute
  • 971 Substitute with incrementing numbers
  • 1114 Step increment and replace
  • 1501 Substitute last search

See also: substitute in buffers/files[]

  • 382 Search and replace in multiple buffers

References[]

  • :help :substitute
  • :help cmdline-ranges
  • :help pattern
  • :help ‘gdefault’
  • :help registers
  • :help :s_flags

[]

 TO DO 
The large «see also» section may be useful to readers. We need to merge some of the related tips (but don’t make the result too complex). I included the tip numbers to help editors keep track.

Want a short section mentioning that simple substitutes are often best handled by searching then manually changing (and pressing . to repeat the last change). Additionally, you can decide how to change each instance. See Copy or change search hit for a technique where you can press n to find the next instance, then type cs to change the search hit to whatever.


Has there been a change recently with how %s works? Somehow i can use both <c-r> and =@ as replacers, but I can’t use them as searches and replacements.

If you describe exactly what you do and what happens I might be able to help although see asking questions. JohnBeckett (talk) 02:15, June 1, 2019 (UTC)

To find and replace all instances of a word in vim, I use

%s/word/newword/g

How do I change this so that it only finds instances of «word» that are whole words?

Greg Bacon's user avatar

Greg Bacon

133k31 gold badges187 silver badges245 bronze badges

asked Nov 22, 2009 at 11:51

neuromancer's user avatar

neuromancerneuromancer

53.1k78 gold badges166 silver badges223 bronze badges

1

You can use < to match the beginning of a word and > to match the end:

%s/<word>/newword/g

answered Nov 22, 2009 at 11:53

sth's user avatar

6

For case-sensitive replace.. you can use «C»

:%s/<word>C/newword/g

It replaces only «word» with newword leaving others like Word,WORD… unreplaced.

answered Nov 24, 2009 at 20:25

Naga Kiran's user avatar

Naga KiranNaga Kiran

8,5355 gold badges43 silver badges52 bronze badges

3

  • First install Vim.

  • To install the packages, first install ‘vundle’ using following command. Use ‘git-shell’ to run this command in Windows.

    git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    
    (in Windows : use 'git-shell' to run below command)
    git clone https://github.com/VundleVim/Vundle.vim.git C:/Users/<Username>/.vim/bundle/Vundle.vim
    
  • Copy and paste the .vimrc file in the home directory.

  • In Windows, paste in the .vimrc file at C:/Users/<Username>/; and change the line “set rtp+= …” in .vimrc with correct location of “Vundle.vim” i.e. “set rtp+=C:/Users/<Username>/.vim/bundle/Vundle.vim”.

  • Use double quote to comment/uncomment the packages in .vimrc file e.g. ” Plugin ‘mattn/emmet-vim’ will not install the package “emmet-vim”. Or add some more packages in .vimrc file as required.

  • After selecting the packages, open vim and run the command -> :PluginInstall and it will install the all the plugins.

  • Use :help <plugin name> to see the list of operations.

1.1. Starting Vim¶

Commands Descriptions
:w save file
:w <filename> save file as <filename> and keep the current file open
:sav <filename> save file as <filename> and open <filename>
:q quit (if already saved)
:q! quit without saving
:e <filename> open new/existing <filename> in new buffer
:wq save and quit
:bn go to next buffer i.e. file
:b <filename> go to buffer with <filename>
:bd close current file without exiting vim
:bd! close current file without exiting vim and ‘no modification’
:vim * open all files in the directory (all in same buffer)
:vim file1 file2 file3 open file1, file2 and file3 in vim
:n go to next file
:n <filename> go to file name
:prev go to previous file
ctrl-Z suspend vim
fg bring forground vim

1.2. Undo/Redo¶

Commands Descriptions
u undo
crtl-r redo

1.3. Insert¶

Commands Descriptions
i insert mode at cursor
I insert mode at beginning of the line (i.e. first character of line)
s delete character under the cursor and enter into insert mode
S delete the line and go to insert mode from the beginning of same line
a insert mode after the cursor
A insert mode at the end of line
o insert mode on below line
O insert mode at bottom line
C delete from cursor to end of line and go to insert mode
r replace current character
R replace characters until Esc is pressed (i.e. same as insert button in keyboard)

1.4. Copy/Paste/Delete¶

Commands Descriptions
y yank (copy)
yiw copy the word
yw copy the word after the cursor
yy or Y copy the line
y$ copy till end of the line from current location of cursor
“+y copy to clipboard e.g. “+yiw will copy the word in clipboard
<F3>y same as above (use <F3> for clipboard, remapped in .vimrc)
<F3>p paste from clipboard (see above line as well)
p paste after cursor (remapped as ]p in .vimrc )
]p paste with indentation
P paste before cursor
ctrl-P paste from clipboard (remapped in .vimrc)
shift insert paste from clipboard (remapped in .vimrc)
d<command> delete<command>
diw delete word (and stay at normal mode)
ciw delete word (and go to insert mode)
dw or cw delete word after the cursor
dd or cc delete line
D or C delete till end of line
x delete character (delete)
X delete character (backspace)
. repeat previous operation

1.5. Paste in search or colon commands¶

  • Following commands can be used at command mode during search or color commands e.g. :w ctrl r ctrl w etc.
Commands Descriptions
ctrl r “ paste the last copied data
ctrl r ctrl w paste the word under cursor
ctrl r % print the naem of current file
shift insert paste the data from clipboard

1.6. Search¶

Commands Descriptions
/ forward then use n/N for next/previous match
? backward
* (asterisk) word under cursor forward (exact match)
g* word under the cursor (partial match)
# word under cursor backward (exact match)
g# word under cursor backward (partial match)
/<word1> search for exact match for “word1”
:set ignorecase use this option for avoiding case-matches
:set noignorecase use this option for case-matches

1.7. Replace¶

  • Use ‘c’, ‘g’, ‘gc’ and other combination to perform the desired replacement.
Commands Descriptions
:s /word1/word2 substitute word1 with word2 in current line (only first occurrence)
:s /word1/word2/c substitute word1 with word2 in current line after confirmation (only first occurrence)
:s /word1/word2/g substitute word1 with word2 in current line (all occurrence)
:s /word1/word2/gc substitute word1 with word2 in current line ater confirmation (all occurrence)
:1,4 s /word1/word2 substitute word1 with word2 in lines 1 to 4 (only first occurrence in each line)
:%s /word1/word2/g replace all occurrences
:%s /word1/word2/gc replace all occurrence after confirmation
:%s /ctrl-r ctrl-w/word2/gc replace all occurance of the word under cursor after confirmation (exact match)
:s /<word1>/word2 substitute exactly matched “word1” with word2 in current line

1.8. Indentation¶

Commands Descriptions
>> Right indent the current line
5>> Right indent 5 lines
<< De-indent line
5== Re-indent 5 lines
>% Increase indent of a braced or bracketed block (place cursor on brace first)
=% Reindent a braced or bracketed block (cursor on brace)
<% Decrease indent of a braced or bracketed block (cursor on brace)
]p Paste text, aligning indentation with surroundings
=i{ Re-indent the ‘inner block’, i.e. the contents of the block
=a{ Re-indent ‘a block’, i.e. block and containing braces
>i{ Increase inner block indent
<i{ Decrease inner block indent
Commands Descriptions
:retab convert existing tabs to spaces

1.9. Mouse settings¶

Commands Descriptions
:behave mswin mouse functionality will work as windows
:behave xterm mouse functionality will word as x-windows

1.10. Command/Visual Mode¶

Commands Descriptions
Esc or crtl-[ command mode
v visual mode
crtl-v visual block mode

1.11. Cursor movement¶

Note

To run the ‘ctrl-]’ and ‘ctrl-T’ command, we need to create the tags first. In the below command, the ‘tags’ will be created for all the python files in the directory, which will be stored in a file ‘tags’,

(run the following command in shell)
ctags -R *.py
Commands Descriptions
h left
j down
k up
l down
w forward to the beginning of next word
3w forward 3 words
W forward to the beginning of next word (only spaces are the end of word)
b backward to the beginning of next word
B backward to the beginning of next word (only spaces are the end of word)
e forward to end of next word
E forward to end of next word (only spaces are the end of the word)
gg go to first line of page
G go to end line of page
10G go to 10th line
10gg go to 10th line
0 go to first character of line
$ go to end character of line
^ go to first non-black character of line
M go to middle of the screen
fa go to next a in current line
Fa go to previous a in current line
ta go to end of next a in current line
Ta to to end of previous a in current line
ctrl-o go to previous location e.g. we went to line 10 from line 18, ctrl-o will go to line 18 again
ctrl-i or Tab go to next location i.e. go to line 10 again from line 18.
gd go to the local declaration of the word under cursor
gD go to the global declaration of the word under cursor
g* search for the word under the cursor
g# same as g* but in backward direction.
gf go to the filename under the cursor, use ctrl-o to go back
ctrl-] go to tag definition (a tag can be a function or variable name etc.); use ctrl-o to go back
ctrl-T go back to previous loation from where ctrl-] was exectued

1.12. Screen movements¶

Commands Descriptions
ctrl-d move half screen down
ctrl-f page down
ctrl-e move one line down
ctrl-u move half screen up
ctrl-b page up
ctrl-y move one line up
z<Enter> move current line to the top of screen (with cursor at the beginning)
zt move current line to the top with without changing the location of cursor
move current line to the center of screen (with cursor at the beginning)
zz move current line to the center of screen (without moving cursor)
z- move current line to the center of screen (with cursor at the beginning)
zb move current line to the center of screen (without moving cursor)

1.13. Unix Shell¶

Commands Descriptions
:shell go to unix shell
exit type exit in unix shell to come back in Vim

1.14. Registers¶

Commands Descriptions
“ayy copy line in register ‘a’
“ap paste content of register ‘a’
Capital letters append the new value to previously stored values
“Ayy copy line and append to previous value in register “a”
Then use “a to paste the value in register ‘a’
“=3*2<Enter>p paste the result i.e. 6 at the current cursor location
:registers display the values in all the registers
:registers abc display the values of registers a, b and c

1.15. Multiple Files¶

Commands Descriptions
:arg grep -l ‘import’ *.py open all files in current folder which contains word ‘import’

1.16. Mark¶

Commands Descriptions
ma mark the line with name ‘a’ (use a-z or 0-9)
  Next go to some other line and excute following command
d’a delete till line which is marked as ‘a’
:marks show the list of marks
‘a go to mark a

1.17. Sorting¶

Commands Descriptions
!10G (press enter) sort (press enter) it will sort first ten lines according to name
!G (press enter) sort (press enter) it will sort all the lines according to names
!!ls go to terminal, run ls command and print the output on the file (i.e. print list of file in current directory)
!!dates go to terminal, run date command and print the output on the file

1.18. Printing the code¶

Commands Descriptions
:hardcopy <filename.pdf> open the printing-instructions-window
:TOhtml and then save the file Save in html format, use :colorscheme default for white background

1.19. Mapping¶

  • Please read the comments in .vimrc file for more commands and details
  • comment/uncomment the command using double quote as per requirement.
Commands Descriptions
:map display the key-mappings,

1.19.1. Copy/paste from clip board¶

Use <F3> and then normal copy/paste command from clipboard.

Copy/paste to clip board  
<F3> is remapped nnoremap <F3> “+
<ctrl-P> is remapped nnoremap <C-P> “+]p (paste with indentation)
<F3>yiw or <F3>yy etc. copy the word or line etc. in clipboard
<F3>p paste the data from clipboard

1.19.2. Disable arraow keys¶

Below code can be used in .vimrc file

“Key mappings : disable arrow keys
no <left> <Nop>
no <down> <Nop>
no <up> <Nop>
no <right> <Nop>
ino <down> <Nop>
ino <left> <Nop>
ino <right> <Nop>
ino <up> <Nop>

1.19.3. Code execution¶

“python commands
” Execute : F9 (Below code is used in .vimrc file)
:autocmd FileType python :nmap <F9> :! clear <CR> :! python % <Enter>
“C/C++ commands
“Compile : F9 (Below code is used in .vimrc file)
:autocmd FileType c,cpp :nmap <F9> :! rm -r out <CR> :! clear <CR> :! g++ % -o out <Enter>
“Run : Ctrl+F9 (Below code is used in .vimrc file)
:autocmd FileType c,cpp :nmap <C-F9> :! clear <CR> :! ./out <CR>

1.20. Buffer¶

Commands Descriptions
:bn go to next buffer i.e. file
:b <filename> go to buffer with <filename>
:bd close current file without exiting vim
:bd! close current file without exiting vim and ‘no modification’

1.21. Split windows¶

Commands Descriptions
:split split window in two part and display current file in both window
:split <filename> open <filename> in split window
:5 split <filename> open <filename> in new split window with width of 5 line
:new split window in two part with second window as blank
crtl-w j go to below split window
crtl-w k go to above split window
crtl-ww, crtl-w w go to next split window
crtl-w + increase the width of split window by one line
5 crtl-w — decrease the width of split window by 5 line
crtl-w = make all split window of equal size
crtl-w _ maximize the current split window

1.22. Auto completion¶

Commands Descriptions
ctrl-p,ctrl-n auto complete by looking previous/next words (use ctrl-p or ctrl-n to change the words from list)

1.23. Text files¶

Commands Descriptions
:set textwidth=50 change the line after 50 character
:1,5 center 50 textwidth = 50 and center the lines 1 to 5
:1,5 right 50 textwidth = 50 and right justify the text on lines 1 to 5
:1,5 left 4 left margin = 4 for lines 1 to 5
Use $ for end of the line as shown below,  
:1,$ center 50 textwidth=50 and cneter all the line
or use % sign for the file (results is same as above,  
:% center 50  
:set wrap turn the wrap words on
:set nowrap turn off the wrap words

1.24. Macros¶

Commands Descriptions
qa start recording and store in reg ‘a’. Then perform certain operations. press ‘q’ again to stop recording.
@a execute macro
3@a repeat macro 3 times

1.25. More commands¶

Commands Descriptions
ctrl + g name of current file
ctrl + u move half screen up
ctrl + d move half screen down
J join line below with current line
3J join below two line with this line (not 3)
z= spell suggestion
~ change case of letter
:digraphs to see the list of symbols e.g. copyright etc.

1.26. Block Visual Mode¶

Add same items in the beginning/end/middle of all the lines

Commands Descriptions
crtl-v select the block with cursor movement
press
I (insert before)
or A (insert after)
or c (replace)
type the text -> press Esc -> block will be replaces by text

1.27. Zoom Screen¶

Commands Descriptions
Zoom in crtl-+
Zoom out ctrl–

1.28. Save session¶

Commands Descriptions
:mksession name.vim save session
:mksession! name.vim override session
:source name.vim load session

1.29. Folding¶

Use space (remapped in .vimrc) at the line below the function definition for folding/unfolding the code.

1.30. Plugins¶

First install ‘vundle’ using following command. Use ‘git-shell’ to run this command in Windows.

  • git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
  • After that copy and paste the .vimrc file in the home directory (in Windows paste in the director C:/Users/<Username>/)
  • Use double quote to comment/uncomment” the packages in .vimrc file e.g. ” Plugin ‘mattn/emmet-vim’ will not install the package “emmet-vim”. Or add some more packages in .vimrc file as required.
  • After selecting the packages, open vim and run the command -> :PluginInstall and it will install the all the plugins.
  • Use :help <plugin name> to see the list of operations.

1.30.1. NERDTree¶

Commands Descriptions
NERDTree turn on the directory structure
NERDTree! disable the directory structure
m then use various operations for delete, and create files.
e.g  
m-a meher create a file with name meher
m-a meher/ create a folder with name meher

1.30.2. Surround¶

Commands Descriptions Results
ysiw” add “” to the word Meher -> “Meher”
ds” delete surround quotes “Meher” -> Meher
cs[( or cs]) change surround [] by () [2+3]/2 -> (2+3)/2
cst<h1> change <p> tag to <h1> <p>Meher Krishna</p> -> <h1>Meher Krishna</h1>

1.30.4. vim-table-mode¶

Follow the below steps to create the ‘rst-table’ in Vim,

  • Enable/Disable table mode using ‘:TableModeEnable/TableModeDisable’ or using ‘:TableModeToggle’,
  • Type column-names e.g. |Col1 | Col2| and press enter
  • Then press | twice to create the table. Do the same to add more lines in the table.
  • Also, go above the |Col1 | Col2| and press | twice (required for correct rst-table-format)

1.30.5. vim-extline¶

This is used to underline the text, which is required for making Headings in .rst document.

  • Type the symbols (in insert mode) e.g. = and then press ctrl-l ctrl-l to complete it.
  • Or press ctrl-l and then press the symbol,
  • Or press ctrl-l and then press a number e.g. 1, 2 etc. This is autocomplete the underline base on heading levels.
  • Some more commands are listed below,
Commands Descriptions
ctrl-l ctrl-l Auto-line update
ctrl-l ctrl-h Horizontal line update
ctrl-l ctrl-u Change to underlined title
ctrl-l ctrl-o Change to overlined title
ctrl-l ctrl-i Change to underlined and overlined title
ctrl-l = or = ctrl-l Force Section heading (with = as underline)
ctrl-l 2 Force Section heading (level 2)

1.30.6. ConqureShell¶

Use :ConqueTermSplit to start the terminal in the Vim.

1.30.7. Airline¶

Airline theme plugin for better view e.g. display name of file, line number, column number etc.

Introduction

Manipulating text and making multiple edits at once is crucial when working in Vim or its older version Vi.

As a popular Linux text editor, Vim offers several practical ways to find and replace terms quickly and efficiently.

This tutorial shows how to use the find and replace function in Vim/Vi and keep track of all the changes.

Vi/Vim - Find and Replace

Note: If you don’t have Vim, check out these tutorials and learn how to install the text editor on CentOS or Ubuntu.

Find and Replace Methods

Finding and replacing text patterns in Vim simplifies navigation and changes in large files.

Hence, Vim offers two ways to search and replace text, depending on whether a single change or multiple edits are necessary.

Warning: Vim must be in normal mode to execute commands. Go back to normal mode with the Esc key.

Slash and Dot Command

Use the slash and dot command to find and replace a single occurrence of a word in Vim.

Open a file in Vim and follow these steps:

  1. Press the slash key (/).
  2. Type the search term to highlight it in the text and hit Enter.
Vim the Slash and Dot Command Using the Slash Key Terminal Output
  1. Use the Esc key to return to normal mode.
  2. Type cgn and enter the replacement term.
Vim the Slash and Dot Command With the Replacement Term Terminal Output
  1. Go back to normal mode.
  2. Hit n to move to the next search term occurrence.
Vim the Slash and Dot Command - Using n Terminal Output
  1. Press the dot (.) key to replace the next occurrence with the same replacement term.
Vim the Slash and Dot Command - Dot Terminal Output

Substitute Command

The substitute command :s is more versatile than the slash and dot command.

The basic :s command syntax is:

:s/search_term/replacement_term/

The command searches for the search_term in the current line, the line where the cursor is. Next, :s changes the search_term to the replacement_term.

For example, to find the term vi in the current line and replace it with Vim, use the following command:

:s/vi/Vim/
Vim the Substitute Command Finding a Term Terminal Output

Hit Enter and the terminal shows that the string vi changed to Vim:

Vim the Substitute Command Replacing a Term Terminal Output

However, :s offers much more than the basic search and replace function. For instance, the command accepts different options and flags. The complete syntax for the substitute command looks like this:

:[range]s/search_term/replace_term/[flags] [count]

These options and flags help specify the search. For example, to find all occurrences of vi in the current line, add the g flag.

:s/vi/Vim/g
Vim the Substitute Command With g Flag Process Terminal Output

Hit Enter to replace both instances with Vim:

Vim the Substitute Command With g Flag Result Terminal Output

Moreover, confirm each substitution with the c flag:

:s/vi/Vim/gc
Vim the Substitute Command with c flag Process Terminal Output

Output is the following:

Vim the Substitute Command With c Flag Options Terminal Output

Vim prompts users to choose between several options:

  • Substitute selected match with Y.
  • Skip selected match with n.
  • Replace all matches with a.
  • Quit the command with q.
  • Replace the selected match and quit with I.

However, the ^E and ^Y options are available in some Vim installations. Use them to scroll the screen:

  • Scroll the screen up with Ctrl + E.
  • Scroll the screen down with Ctrl + Y.

Find and Replace Important Considerations

The find and replace tools in Vim, especially the substitute command, offer additional possibilities for a more specific and effective search. Check out how to customize the search and replace operation in the following text.

Search Range

Specifying a range when running the :s command helps users search and replace patterns beyond the current line.

To determine the range:

  1. Add line numbers separated by a comma to find and replace a pattern in specific lines.

For example, substitute all occurrences of vi to Vim from line 1 to line 3:

:1,3s/vi/Vim/g
Vim the Substitute Command With Line Numbers Separated by a Comma Process Terminal Output

The output shows that only the first two instances of vi, in the first three lines, were changed to Vim:

Vim the Substitute Command With Line Numbers Separated by a Comma Terminal Output
  1. Choose the % symbol and add the g flag to find and replace a pattern in the entire file.
:%s/vi/Vim/g
Vim the Substitute Command With % and g Flag Terminal Output
  1. Use a dot (.) and a dollar sign ($) separated by a comma to substitute everything from the current line to the last line.
:.,$s/vi/Vim/g
Vim Substitute Command With the Dot and Dollar Sign Process

Since the current line is also the last line, the output shows that the instances of vi in the last line were changed.

Vim Substitute Command With the Dot and Dollar Sign Command Terminal Output
  1. Combine +/- symbols with numbers to add or subtract lines from the current one.

For example, to substitute each vi with Vim starting from the current line and the next two lines, type:

:.,+2s/vi/Vim/g
Vim the Substitute Command-Using + and- Symbols With Numbers

Case Sensitivity

The find and replace process in Vim is case-sensitive by default. For example, using the :s command to substitute vim (in lowercase) with vi does not work. This is because Vim is always in capitalized in this text. Therefore, use Vim instead of vi as the search term.

To make the find and replace operation case insensitive, use one of the two methods:

  1. Add the i flag.
:%s/vim/vi/gi
Vim Substitute Command With the i Tag Terminal Output

The output shows that both instances of Vim have been found and replaced with vi.

Use the I flag to turn the case-sensitive search back on.

  1. Append c after the search pattern.
:%s/vimc /vi/g
Vim the Substitute Command With the Appended c Terminal Output

The output shows that even though the search term is lower case, the command finds the uppercase Vim in the text.

Adding the /C after a search pattern turns on case-sensitive search.

Word Substitution

The :s command, by default, searches for patterns, not unique words. For example, using vi as the search pattern results in matches where vi is part of a larger word, such as visible.

Vim the Substitute Command Searching for Whole Words Terminal Output

Executing the command in the entire text changes patterns included in other words as well.

Vim Substitute Command Replacing Words Nested in Other Words Terminal Output

Search and replace a whole word with:

:%s/<search_term>/replace_term/

The < symbol marks the beginning and the > symbol the end of a word. For example, to search for the word vi, but not when part of a bigger word, and replace the word with Vim, use:

:%s/<vi>/Vim/g
Vim the Substitute Command Find and Replace Whole Word Terminal Output

Find and Replace History

Running the :s command without any options shows previous substitute operations. In addition, run the :s command and use the up/down arrow keys to move across the document.

More importantly, use the :s command to apply previous substitutes to new text. For example, the history shows that the command replaced all instances of vi with Vim.

Running :s finds any already made substitutes, but also all instances of vi not changed yet.

Vim Substitute Command History Terminal Output

Find and Replace Examples

The find and replace function in Vim has extensive practical use. Thus, outlined below are common substitute command examples.

Find and Replace Entire Lines

Use :s to substitute entire lines in Vim based on a single parameter. For example, substitute every line starting with Do you with Learn more about Vim! using this command:

:%s/^Do you .*/ Learn more about Vim!/g
Vim Substitute Command Replacing Entire Line Terminal Output

The ^(caret) symbol matches the beginning of a line, and * matches the rest of the line.

The output shows the change:

Vim Substitute Command Replacing Entire Line

Change Number in Numbered List

Adding an item in the middle of a numbered list in Vim means that the user has to change numbers in all the subsequent lines.

Vim Adding an Item to a Numbered List

The substitute command changes the numbers of all other articles accordingly. Use this command:

:5,$s/d+/=submatch(0) + 1/
Vim Substitute Command Changing Numbers in a Numbered List

The command consists of:

  • :5,$ — The range from the fifth line to the last line.
  • d+ — The digits sequence as the search term.
  • =submatch(0) + 1 — The replacement term adding 1 to each match.

After executing the substitute command, the output looks like this:

Vim Substitute Command Changed Numbers in a Numbered List

Eliminate Double Spaces

Double spaces are common typing errors, but :s takes care of this quite quickly with:

:%s/[double space]/[single space]/g
Vim Substitute Command Finding Double Space Terminal Output

All spaces in the last line are doubled. After executing the command, the sentence is single-spaced:

Vim Substitute Command Eliminating Double Spaces Terminal Output

Replace Different Words with One

Use the substitute command to substitute different search terms with one replacement term. For example, replace every instance of vi and Vim with This text editor.

:%s/(vi|Vim)/This text editor/g
Vim the Substitute Command Replacing Different Words With One Process

The changed text looks like this:

Vim the Substitute Command Replacing Different Words With One Result Terminal Output

Delete All Pattern Occurrences

Instead of substituting the search term, delete the pattern by omitting the replacement term. For example, delete all instances of Vim with:

:%s/Vim/
Vim Substitute Command Deleting Words Terminal Output

Conclusion

After reading this tutorial, you know how to find and replace text in Vim.

Next, check out and download this useful Vim Commands Cheat Sheet to learn other common Vim commands.

How do you search for a text in Vim?

Press the / key, type your search text and press enter. This is just like the less command.

But this method of finding text doesn’t allow you to replace the found result.

Let me share how you can find and replace in Vim.

:%s/foo/bar/gci

The above command will run a case-insensitive search to find all the occurrences of your search term (foo) with the new term (bar). With the flag c, it asks to confirm before replacing any substitution.

Let me go into detail and explain things more clearly.

Using the substitute command to find and replace text in Vim

I guess you already know that to run a command in Vim, you must be in the normal mode (also known as command mode). Press Esc key to enter this mode.

Vim has a handy command :substitue, can also be used with the shorter version :s.

Below is the general syntax of the substitute command:

:[range]s/{pattern}/{string}/[flags] [count]

Let’s break down this syntax. Anything between the square brackets ‘[]’ is optional.

  • range : This part of the syntax can be used if you want the substitution between said lines. If you do not mention a range, it will only substitute text on the current line. (I have shared a table for range)
  • pattern : Here is where you specify the text that you want to replace.
  • string : This is the string which will replace the pattern.
  • flags : To replace all occurrences of the search pattern, use the g flag. You can specify if you want the match to ignore case, use i flag. To manually confirm each search and replace operation, use the c flag.
  • count : Number of lines to replace text in.
Range Description
. Current line
$ Last line
% All lines
x Line number x
.,+x From current line until additional x lines

Examples of finding and replacing in Vim

Let’s go over a few examples that demonstrate the use of the substitute command in Vim.

Below is the screenshot of the file I will be using to demonstrate the usage of substitute command in Vim.

Basic text replacement

For this example, I made sure that the string ‘Hello’ occurred several times in at least one line and multiple times in the file.

I want to replace ‘Hello’ with the string ‘HI’. Below is the Vim command to do that:

:%s/Hello/HI/g

Replace with confirmation

To substitute text, but want a confirmation every time you do it, you can use the c in the substitute command.

:%s/Hello/HI/gc

As you can see from the video, Vim asks me for a confirmation every single time before it substitutes a pattern.

You also have a prompt that looks like the following line:

replace with HI (y/n/a/q/l/^E/^Y)?

The options from the prompt have the following meaning:

  • y: yes
  • n: no
  • a: all
  • q: quit without substituting, but it does not undo once you have already substituted text
  • l: substitute this and exit (think of ‘last’)
  • ^E: Scroll up (does not work in vim-tiny)
  • ^Y: Scroll down (does not work in vim-tiny)

Case-insensitive replacement

When you want to substitute text regardless that if it is in uppercase or lowercase, in that case (haha) you should use the i flag in the substitute command.

:%s/hello/HI/gi

If you notice, all occurrences of ‘hello’ or ‘Hello’ and even ‘hELLO’ are replaced with ‘HI’. This is a case insensitive pattern substitution.

Every ‘hello’ is replaced with ‘HI’ even though most ‘hello’ have an uppercase ‘H’ in it.

Replace text in single line in Vim

To substitute text in a single line, we need to specify the range that limits the scope of substitution to the current line.

For that, it is better to use the . range descriptor.

:.s/Hello/HI/g

Look how only the first line got affected

As you can see, only the pattern in the first line got substituted because I used the period ‘.’ range descriptor.

Bonus tip: Using a different delimiter

Looking at the syntax of the substitute command, I mentioned that the pattern and string are separated by a forward slash ‘/’.

But what if you had text with lots of forward slashes in pattern/string, like a path, that repeated everywhere in the file? Escaping forward slashes can be tedious and it can be easily missed sometimes.

So, instead of using the forward slash character as a delimiter, you can use a different delimiter instead.

A few delimiter characters that I have seen being used are #, _ and @.

Here is a gif that shows demonstration of using @ as a delimiter instead of /.

Conclusion

Substituting text can be a common occurrence and Vim has you covered with a powerful way to search and replace patterns with a string. You can even mix regex in Vim’s substitution command.

If you are interested in learning more than just the Vim Basics, I highly recommend using this program by Jovica Ilic.

Mastering Vim Quickly — Jovica Ilic

Exiting Mastering Vim Quickly From WTF to OMG in no time

Jovica Ilic

Team LHB

Team LHB indicates the effort of a single or multiple members of the core Linux Handbook team.

Понравилась статья? Поделить с друзьями:
  • View comment in word
  • View chart in excel
  • View buttons in excel
  • View button in excel
  • View all the comments in word