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.
Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.
Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.
The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string . The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string . To confirm each replacement, add the confirm ( c ) flag after the global flag.
Find and Replace One Occurrence at a Time Execute a regular search with / . Use the keystroke cgn on the first result to replace it. Type n or N to go to the next result. Use . to replace the occurrence with the same replacement, or go to the next result if you want to keep it.
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.
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
You can use .
for the current line, like:
:.s/old/new/
This will change old
by new
in the current line only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With