Find and Replace within selection in `vi`

2019-03-08 05:11发布

How do I do a Find and Replace within a selection in vi?

5条回答
淡お忘
2楼-- · 2019-03-08 05:32
我只想做你的唯一
3楼-- · 2019-03-08 05:39

If you want to do a global search and replace (with optional regexes) for all instances in the file, I would do the following:

:%s/foo/bar/g

Omit the g to do a local replace.

查看更多
贼婆χ
4楼-- · 2019-03-08 05:41

Most of the other solutions suggested here work over the ENTIRE line in which the selection occurs, which may not be what you want.

To search and replace ONLY in the selection, first visually select the text, then use a command like so:

:%s/\%VSEARCH/REPLACE/g

This will do the search and replace only in the visually selected section, replacing SEARCH with REPLACE. If you have more than one line selected, this will work over multiple lines too.

查看更多
Root(大扎)
5楼-- · 2019-03-08 05:47

Select the text in visual mode (I assume that's what you're doing), then press : to start typing a command, you'll see something like this appear in the command line:

:'<,'>

That means that the command will apply to the selection. Then type s/search/replace/ and hit enter. (Add a g after the third slash if you want to replace all matches, and a c if you want a confirmation for every replace)

查看更多
孤傲高冷的网名
6楼-- · 2019-03-08 05:48

If you used Visual Mode to select, then:

:'<,'>s/regex/replacement/options

VIM will place the range ('<,'>) automatically if you go into Command Line Mode (by pressing ':') from within Visual Mode.

查看更多
登录 后发表回答