How to change a string in the vim editor?

非 Y 不嫁゛ 提交于 2019-12-13 10:00:28

问题


I am trying to replace a string with slashes in vim editor

ex: foo to abc/def/foo. Any suggestions?


回答1:


The title and the content of your question don't match.

:help pattern and :help :substitute are a bit overwhelming but very useful as regular expressions are at the heart of Vim.

Vim regular Expressions 101 is a more concise resource.

Anyway, given the following sample text:

bar baz foo baz bar

your goal can be achieved in a variety of ways. Here are some of them:

:s/foo/\/abc\/def\/foo
:s/foo/\/abc\/def\/&
:s+foo+/abc/def/&

A few notes:

  • In the replacement part, & stands for "the matched text". If the match is foo, & is foo. Of course there's not much benefit in using & over foo, here, but wait until you have a more complex pattern…

  • Because Slashes are used to separate the search part and the replace part, you need to escape the actual slashes in both parts for your substitution to work.

  • You can use many other symbols instead of slashes to separate the search and the replace parts. This is very useful when you know you'll need to escape too many slashes.




回答2:


To do a string replace in vim you must first be out of visual or insert mode. Then type ':' to get to execute a vim command. The substitution command in vim starts with '%s'. Putting everything together you have

:%s/thingyouhave/thingyouwant/

In your stated example you need to escape the '/' in your file name with back slashes '\'.

:%s/foo/abc\/def\/foo/

One other useful bit is putting 'gc' at the end of your expression; this will prompt you for verification before executing each change. This is useful if you want to change some of the instances of an expression or are unsure if what you are doing is correct.

:%s/foo/abc\/def\/foo/gc


来源:https://stackoverflow.com/questions/13355809/how-to-change-a-string-in-the-vim-editor

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