Vim - Search and Replace

Updated: 2020-06-29

Replace

:s vs :%s:

Search current line:

:s/Search/Replace/FLAG

Search whole text:

:%s/Search/Replace/FLAG

FLAG:

  • g: global, replace all occurrences
  • c: confirm before replace
  • i: ignore cases
  • /{pattern} search forward
  • ?{pattern} search backward
  • n: Repeat search in same direction.
  • N: Repeat search in opposite direction.
  • /<ENTER> Repeat search forward.
  • ?<ENTER> Repeat search backward.

inline search

  • f{char}: Find (move cursor to) next occurrence of x in the line, where x stands for any character.
  • F{char}: Find (move cursor to) previous occurrence of x in the line.
  • t{char}: Find (move cursor to) character before next occurrence of x in the line.
  • T{char}: Find (move cursor to) character after previous occurrence of x in the line.
  • ;: Repeat previous find command in same direction.
  • ,: Repeat previous find command in opposite direction.

Matching

:match Group /pattern/

Group: color group pattern: regex

see the complete color group

:so $VIMRUNTIME/syntax/hitest.vim

e.g.

:match ErrorMsg /^Error/

remove highlight

:match NONE

Mark color characters after a certain column: every character after the 73rd character will be marked as an error

:match ErrorMsg /\%>73v.\+/

Mark tabs not used for indentation in code

:match ErrorMsg /[^\t]\zs\t\+/