vim replace a string when a change occurred in another place

隐身守侯 提交于 2019-12-24 04:58:13

问题


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 only foo occurrences were found, not foobar or myfoo)
  • change the name: caw<new name><ESC>
  • repeat until done: press n to 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.

  1. Change program name:

    ciW
    foobar<Esc>
    
  2. Move to end of program:

    /End<CR>
    $
    
  3. Repeat change:

    .
    


来源:https://stackoverflow.com/questions/31000853/vim-replace-a-string-when-a-change-occurred-in-another-place

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