问题
Say, I have a file:
Program foo
<program text>
End Program foo
Is it possible that if I change the word foo in the first line to bar (which may not be the first line of the file), the last line's foo will also be changed to bar automatically?
回答1:
You could use a global command and a find and replace to mark the start en stop of the area that should be replace like this
:g/^Program foo$/.,/foo$/s//bar
Breakdown
:g Starts the global command
/^Program foo$ Search for Program foo where the line starts with Program and ends with foo
/.,/foo$/ for each mach, expand the rang until the next foo at the end of the line
s//bar substitute your last search results with bar
回答2:
I usually do such things as follows:
- move the cursor over the name to be changed
- press
*or#(this searches for this word forwards or backwards, respectively, and only for the word as a whole, so in your example onlyfoooccurrences were found, notfoobarormyfoo) - change the name:
caw<new name><ESC> - repeat until done: press
nto jump to the next possible occurrence, press.to repeat the name changing operation if required
You could also use a single search-and-replace command like :%s/\<foo\>/new_name/gc and then press y or n for every foo occurrence, but personally I prefer the above method because it saves me from typing foo and from remembering to put \< and \> around it (#/* do this for me).
If you are sure that you want to replace all occurrences of foo to bar, you can omit the confirm flag from the search-and-replace command, which will then be the shortest way to do what you want that I can think of.
回答3:
You can try this plugin out, i think it would exactly what you want:
https://github.com/terryma/vim-multiple-cursors
回答4:
Assuming your cursor is on the program name this can be done pretty easily.
Change program name:
ciW foobar<Esc>Move to end of program:
/End<CR> $Repeat change:
.
来源:https://stackoverflow.com/questions/31000853/vim-replace-a-string-when-a-change-occurred-in-another-place