In Vim, how to search and replace in current line only?

喜欢而已 提交于 2020-11-30 20:56:16

问题


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.


回答1:


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.




回答2:


You can use . for the current line, like:

:.s/old/new/

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




回答3:


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




回答4:


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/n - self explanatory
a - replace all occurrences
q - quit
l - replace the current and stop (last)
^E/^Y - ctrl+e and ctrl+y - scroll down and up respectively.

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



来源:https://stackoverflow.com/questions/46181488/in-vim-how-to-search-and-replace-in-current-line-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!