vimtricks.wiki Concise Vim tricks, one at a time.

How do I search and replace text across an entire file?

Answer

:%s/old/new/g

Explanation

The :%s/old/new/g command replaces all occurrences of old with new across every line in the file.

How it works

  • : enters command-line mode
  • % means "every line in the file"
  • s is the substitute command
  • /old/new/ specifies the search pattern and replacement
  • g flag means "all occurrences on each line" (without it, only the first match per line is replaced)

Example

Given the text:

foo bar foo
foo baz foo

Running :%s/foo/qux/g results in:

qux bar qux
qux baz qux

Tips

  • Add c flag for confirmation: :%s/old/new/gc prompts before each replacement
  • Add i flag for case-insensitive: :%s/old/new/gi
  • Use \< and \> for whole-word matching: :%s/\<old\>/new/g
  • Replace only in a visual selection by selecting text first, then typing :s/old/new/g

Next

How do I edit multiple lines at once using multiple cursors in Vim?