Skip to content

/commands/vim/vim-search-and-replace

Vim search and replace: :%s/old/new/g and its flags

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · VIM - Vi IMproved 9.2 (2026 Feb 14updated 2026-10-20
tool
Vim / Neovim
versions
Vim 8, Vim 9, Neovim
os
any

:%s/old/new/g replaces every old with new in the whole file: % is the range (all lines), s is :substitute, and the g flag replaces every match on a line instead of only the first. Add c to confirm each replacement and i to ignore case.

Forms you will use

CommandReplaces
:s/old/new/the first match on the current line
:s/old/new/gall matches on the current line
:%s/old/new/gall matches in the file
:%s/old/new/gcall matches, asking y/n/a/q for each
:%s/old/new/giignoring case
:'<,'>s/old/new/ginside the visual selection (press : after selecting)
:10,20s/old/new/glines 10 to 20
:%s/\<id\>/user_id/gwhole word id only, not valid or idle
:%s#/usr/local#/opt#gany delimiter works, handy for paths

Try them in batch mode

bash
printf 'color colour Color\nid valid idle id\nuse /usr/local/bin\n' > notes.txt
vim -Nu NONE -i NONE -es \
  -c '1s/colou\=r/hue/gi' \
  -c '2s/\<id\>/user_id/g' \
  -c '3s#/usr/local#/opt#' \
  -c 'wq' notes.txt
cat notes.txt

Output

hue hue hue
user_id valid idle user_id
use /opt/bin

Vim regular expressions are "magic" by default: \= (or \?) means "optional", \< and \> are word boundaries, and +, ?, ( and | need a backslash. Start the pattern with \v ("very magic") to write them like other regex engines: :%s/\v(\w+) (\w+)/\2 \1/.

Useful extras

  • & in the replacement is the whole match; \1 … \9 are groups; \r inserts a line break.
  • :%s//new/g with an empty pattern reuses the last search, so search with / or * first, then replace.
  • :%s/x/y/gn counts matches without changing anything.

Sources