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
:sis the substitute command, defaulting to the current line/old/is the search pattern/new/is the replacement stringgis 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
gflag, only the first occurrence on the line is replaced - Use
:%s/old/new/gto replace across the entire file - Use
:%s/old/new/gcto replace across the file with a confirmation prompt for each match - Use
:s/old/new/ifor 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:swithout arguments to repeat the last substitution on the current line - Use
\vat the start of the pattern for "very magic" mode, which makes regex syntax closer to Perl/Python