Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Registers, Macros and Search

Vim Substitute and Global: Find and Replace at Scale

Master :s with ranges, flags and backreferences, confirm each change with c, and use :g and :v to run commands on matching lines. Includes runnable models.

Search finds; substitute changes. The :substitute command is Vim's find-and-replace, and its partner :global runs any command on every line that matches a pattern. Together they handle most bulk edits that do not need a macro. This lesson covers both from the basics to common recipes.

The substitute command

VIM
:[range]s/pattern/replacement/[flags]
  • Without a range it acts on the current line.
  • :%s/old/new/g acts on every line (% means the whole file), replacing every match (g flag).
  • Without g, only the first match on each line is replaced.

Common ranges:

Range Lines
% the whole file
5,12 lines 5 to 12
.,$ from the current line to the end
'<,'> the last Visual selection (filled in for you)
/start/,/end/ between two patterns
.,+4 the current line and the next four

Flags

Flag Meaning
g all matches on each line
c confirm each replacement
i / I ignore case / match case
n only count matches, change nothing
e do not show an error if there is no match
& reuse the flags of the previous substitute

The confirm flag asks at every match: y yes, n no, a all remaining, q quit, l last (do this one and stop). Use c when a pattern could match things you do not want to change. :%s/foo//gn prints N matches on M lines, a safe preview.

Replacement text and backreferences

In the replacement, & means the whole match and \1 to \9 are the captured groups from \(...\). With very magic \v the group is plain (...):

VIM
:%s/\v(\w+), (\w+)/\2 \1/

This turns Smith, John into John Smith. To insert a literal & write \&. Special replacement tokens:

  • \r inserts a newline (not \n, which inserts a null in the replacement)
  • \t a tab
  • \u and \U uppercase the next character or the following text until \E, and \l and \L do lowercase. For example :%s/\<\w/\u&/g capitalizes the first letter of every word.
  • ~ is the previous replacement.
  • \= evaluates an expression: :%s/\d\+/\=submatch(0)*2/g doubles every number.

A different delimiter

When the pattern contains slashes, change the delimiter to anything else: :%s#/usr/local#/opt#g avoids escaping. Any non-alphanumeric character works, so :s|a/b|c/d| is fine.

JS A model of :s with flags and groups (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows the rule that trips up beginners: without g only the first a on each line changes.

The global command

:g/pattern/command runs an ex command on every line matching the pattern. The default command is p (print), so :g/TODO lists all TODO lines. Examples:

  • :g/^$/d deletes all empty lines.
  • :g/pattern/d deletes lines that match.
  • :v/pattern/d (or :g!/pattern/d) deletes lines that do not match: keep only matching lines.
  • :g/pattern/s/old/new/g substitutes only on lines that match.
  • :g/^/m0 reverses the file (move each line to the top, one at a time).
  • :g/pattern/t. duplicates each matching line (copy below).
  • :g/pattern/normal Atext appends text to each matching line using Normal-mode keys.
  • :g/start/.,/end/d deletes ranges from start to end.

:g works in two passes: it first marks the matching lines, then runs the command on each. That is why :g/x/d is safe even though lines shift while deleting.

JS A model of :g and :v (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Normal on a range

:normal executes Normal-mode keys on each line of a range, and it is the bridge between macros, dot and ranges:

  • :%normal A; appends a semicolon to every line.
  • :'<,'>normal . repeats your last change on each selected line.
  • :g/foo/normal @a runs macro a on every line with foo.

Use Ctrl-v Esc to type an escape character into the command line when the keys include Esc.

Recipes

Goal Command
Trim trailing whitespace :%s/\s\+$//e
Collapse many blank lines to one :%s/\n\{3,}/\r\r/e
Capitalize every word :%s/\<\w/\u&/g
Swap two words around a comma :%s/\v(\w+), (\w+)/\2, \1/
Number lines :%s/^/\=line('.') . '. '/
Wrap words in quotes :%s/\<\w\+\>/"&"/g
Replace word under cursor everywhere :%s/\<<C-r><C-w>\>/new/g
Search and replace in many files :args **/*.js, :argdo %s/a/b/ge | update

The last recipe uses :argdo: it runs a command across the argument list. :cfdo does the same across the quickfix list, and :bufdo across open buffers.

Safety habits

  • Preview with the n flag or the c flag.
  • Remember u undoes the whole substitute in one step.
  • Use \< and \> for whole-word matches: :%s/\<cat\>/dog/g leaves catalog alone.
  • In Neovim inccommand=split shows a live preview of the substitution as you type, a very useful setting (chapter 6).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does :%s/a/b/ do?

    % means the whole file, and without the g flag only the first match per line is replaced.
  2. 2. Which command deletes all lines that do NOT contain TODO?

    :v (or :g!) runs the command on lines that do not match.
  3. 3. In the replacement text, what does \1 refer to?

    \1 is the text matched by the first ( ) group; & is the whole match.
  4. 4. What does the c flag do?

    With c you answer y, n, a, q or l at every match.

Summary

  • :[range]s/pat/repl/[flags] substitutes; % is the whole file, g is all matches, c confirms.
  • & and \1..\9 reference the match and groups; \u, \U and \= transform the replacement.
  • :g/pat/cmd and :v/pat/cmd run a command on matching or non-matching lines.
  • :normal ties ranges to Normal-mode keys, macros and the dot command.
  • Preview with n or c, anchor words with \< \>, and undo with u.

Next: Buffers: Working With Many Files