Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search and replace in current line only?

Tags:

replace

vim

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.

like image 367
mherzl Avatar asked Sep 12 '17 16:09

mherzl


People also ask

How do I search and replace in Vim?

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.

How do you replace a word with another word in Vim?

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.

How do I use global replace in vi?

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.

What is keystroke CGN?

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.


3 Answers

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.

like image 51
Stephen.W Avatar answered Oct 06 '22 18:10

Stephen.W


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

like image 17
Wanda Ichsanul Isra Avatar answered Oct 06 '22 18:10

Wanda Ichsanul Isra


You can use . for the current line, like:

:.s/old/new/

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

like image 48
Toto Avatar answered Oct 06 '22 20:10

Toto