/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
| Command | Replaces |
|---|---|
| :s/old/new/ | the first match on the current line |
| :s/old/new/g | all matches on the current line |
| :%s/old/new/g | all matches in the file |
| :%s/old/new/gc | all matches, asking y/n/a/q for each |
| :%s/old/new/gi | ignoring case |
| :'<,'>s/old/new/g | inside the visual selection (press : after selecting) |
| :10,20s/old/new/g | lines 10 to 20 |
| :%s/\<id\>/user_id/g | whole word id only, not valid or idle |
| :%s#/usr/local#/opt#g | any delimiter works, handy for paths |
Try them in batch mode
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.txtOutput
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…\9are groups;\rinserts a line break.:%s//new/gwith an empty pattern reuses the last search, so search with/or*first, then replace.:%s/x/y/gncounts matches without changing anything.
Sources
Related pages
errors · vimVim: E37: No write since last change (add ! to override)Vim shows E37: No write since last change when you quit or open another file with unsaved edits. Save with :wq, discard with :q!, or set the hidden option.cheat sheets · regexRegex cheat sheet: characters, quantifiers, groups and lookaroundsRegex cheat sheet: character classes, anchors, quantifiers, greedy and lazy matching, groups and backreferences, lookarounds, with tested Python examples.compare · vimVim vs Neovim: what differs and which to chooseNeovim is a Vim fork with Lua configuration, a built-in LSP client, Tree-sitter and modern defaults; Vim keeps Vim9 script and maximum compatibility. Compared.