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

How do I search and replace text only on the current line?

Answer

:s/old/new/g

Explanation

The :s/old/new/g command replaces all occurrences of old with new on the current line only. Unlike :%s which operates on the entire file, :s without a range is scoped to the line where the cursor is.

How it works

  • :s is the substitute command, defaulting to the current line
  • /old/ is the search pattern
  • /new/ is the replacement string
  • g is the flag for "global" — replace all occurrences on the line, not just the first

Example

Given the text with the cursor on the second line:

foo bar baz
foo bar foo bar
foo bar baz

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

foo bar baz
qux bar qux bar
foo bar baz

Only the current line is affected. The other lines remain unchanged.

Tips

  • Without the g flag, only the first occurrence on the line is replaced
  • Use :%s/old/new/g to replace across the entire file
  • Use :%s/old/new/gc to replace across the file with a confirmation prompt for each match
  • Use :s/old/new/i for case-insensitive matching on the current line
  • In visual mode, select a range of lines and then type :s/old/new/g — Vim automatically adds the range markers '<,'>
  • Use & or :s without arguments to repeat the last substitution on the current line
  • Use \v at the start of the pattern for "very magic" mode, which makes regex syntax closer to Perl/Python

Next

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