Skip to content

Substitute commandλ︎

:substitute or :s command highlights the matches for a text pattern and substitute for a new pattern

Neovim :help :substitute
:help :substitute

Subsitute the first matching patterns in the current line

:s/current-pattern/new-pattern/

If the new-pattern text is ommitted, then substitute deletes the current-pattern occurances, e.g :s/current-pattern//

Subsitute all the matching patterns in the current line, g representing all occurances in a line

:s/current-pattern/new-pattern/g

Use % to specify the current buffer as the scope to change all matches

:%s/current-pattern/new-pattern/g

An inclusive line range can be specified to narrow the search

:4,24s/current-pattern/new-pattern/g

. can be used to represent the current line of buffer

$ to represent the last line of the current buffer

:.,$s/current-pattern/new-pattern/g

Match the whole word

:.,$s/\<current-pattern\>/new-pattern/g

Substitute historyλ︎

:s and the Up / Down will navigate through the substitution history for the current session (from when Neovim was last opened if session was not restored)

Confirm replacementλ︎

c option at the end prompt for confirmation to replace each occurance

:%s/current-pattern/new-pattern/gc

y confirms the repacement

l confirms the repacement and quits

n skips the current occurance and goes to the next one

y or Esc to quit substitution

Regular expressionλ︎

regular expressions can be used as a search pattern.

To replace all lines starting with ‘foo’ with ‘NeoVim Rocks’:

:%s/^foo.*/NeoVim rocks/gc

Replace all instances of ‘apple’, ‘orange’, and ‘mango’ with ‘fruit’:

:%s/apple\|orange\|mango/fruit/g

Remove trailing blank space at the end of each line:

:%s/\s\+$//e

Matching caseλ︎

i option disables the default case sensitive search

:%s/current-pattern/new-pattern/gi

Visual Selectλ︎

Use a visual select to search and replace, with confirmation

Note: '<,'> is automatically included when in visual mode and : is pressed to start a command

:'<,'>s/search-text/replace-text/g

A potentially more effecitve approach:

  • visually select the text
  • * to select all matching occurances
  • :%s//replace-text/g