ag@linux:~$

history 17 of 36

VI Editor Search and Replace Commands

Reference for vi search and replace with :s, covering the current line, the whole file, line ranges, marks and the :g command, with confirm and case flags.

Written

From my Linux study notes, 2014. Some commands and versions here are old, so please reuse them carefully. Anything marked "added later", and the notes at the end, explain what has changed since.

Type these in normal mode (press Esc first), then press Enter. In each example, foo is the text to find and bar is the replacement.

:s/foo/bar/g

Change each “foo” to “bar” in the current line.

:%s/foo/bar/g

Change each “foo” to “bar” in all lines.

:5,12s/foo/bar/g

Change each “foo” to “bar” for all lines from line 5 to line 12 inclusive.

:'a,'bs/foo/bar/g

Change each “foo” to “bar” for all lines from mark a to mark b inclusive.

To set the marks first, move to a line and press ma to set mark a, then move to another line and press mb to set mark b.

:.,$s/foo/bar/g

Change each “foo” to “bar” for all lines from the current line (.) to the last line ($) inclusive.

:.,+2s/foo/bar/g

Change each “foo” to “bar” for the current line (.) and the next two lines (+2).

:g/^baz/s/foo/bar/g

Change each “foo” to “bar” in each line starting with “baz”.

:g (global) first finds every line matching the pattern ^baz and then runs the s command on each of those lines.

Notes for today

How the command is built

:[range]s/old/new/[flags]
  • range: which lines. No range means the current line only; % means the whole file.
  • old: the text or pattern to search for.
  • new: the replacement text.
  • flags: options at the end.

Useful flags

Flag Meaning
g Replace every match on the line. Without it, only the first match on each line is replaced.
c Ask for confirmation before each replacement (answer y or n).
i Ignore case (Vim).

For example, to replace throughout the file but approve each change:

:%s/foo/bar/gc

Searching without replacing

  • /foo searches forward for “foo”.
  • ?foo searches backwards.
  • n jumps to the next match, N to the previous one.

Text that contains a slash

File paths contain /, which is also the separator. Either escape each slash with a backslash or use a different separator character such as #:

:%s#/var/www/old#/var/www/new#g

Special characters

The search part is a pattern, not plain text. Characters such as ., *, ^, $, [ and \ have special meanings. To match them literally, put a backslash in front, for example \. to match a full stop.

Mistakes

Press u in normal mode to undo the whole replacement. Nothing is written to disk until you save with :w.