How to search and replace in current line only?

VimReplace

Vim Problem Overview


I see how to search and replace in specific lines, specifying by line number, and how to search and replace using the current line as reference to a number of lines down.

How do I search and replace in the current line only? I'm looking for a simple solution that does not involve specifying line numbers as the linked solutions do.

Vim Solutions


Solution 1 - Vim

Replace all occurrences of str1 with str2 in certain line:

:s/str1/str2/g

remove the g option if you want to replace only the first occurrence.

Solution 2 - Vim

You can use . for the current line, like:

:.s/old/new/

This will change old by new in the current line only.

Solution 3 - Vim

If you want to search and replace all of the matched word in the current line, you could easily use simple substitute (s) with g modifier in command mode.

:s/search/replace/g

If you just want to search and replace the first matched word in the current line, just move away the g modifier from your command.

:s/search/replace/

Ref: :help substitute

Solution 4 - Vim

Confirm (c) and Replace :

:s/foo/bar/gc

Find the occurrence of 'foo', and before replacing it with 'bar' ask for confirmation.

Vim gives you these options :

replace with bar (y/n/a/q/l/^E/^Y)?
  • y - yes
  • n - no
  • a - replace all occurrences
  • q - quit
  • l - replace the current and stop (last)
  • ^E (CTRL + e) - scroll down
  • ^Y (CTRL + y) - scroll up

Now, in your case you can use the combination of y, n and l to achieve your purpose.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmherzlView Question on Stackoverflow
Solution 1 - VimStephen.WView Answer on Stackoverflow
Solution 2 - VimTotoView Answer on Stackoverflow
Solution 3 - VimWanda Ichsanul IsraView Answer on Stackoverflow
Solution 4 - VimHarshaDView Answer on Stackoverflow