Vim 的 Replace by Search

Oct 12 2008

使用 vim 時,最常使用的功能之一就屬 search 了,搭配上 regular expression, highlight search 與 incremental search,我就這樣,使用這種非常原始的方式寫起程式。

有時,我會藉由使用 highlight search 來快速「標示」出一些感興趣的程式碼來,待確定這些都是我要的後,再透過 regular expression replace 來替換掉。

舉例來說,下圖是一段程式碼。
vim_replace_by_search_01

我用 regular expression 來搜尋類似 self[‘ooxx’] 的程式碼(/self\[‘\w*’\]):
vim_replace_by_search_02

快速確認了一下,highlight 的部分都是我要的:
vim_replace_by_search_03

接著重頭戲來了,我想把 self[‘ooxx’] 都改成 self.ooxx,亦即把 dictionary 的 key-value 關係改為 attribute name-value 的型式。於是我可以再老老實實地輸入一次 s/self\[‘\(\w*\)’\]/self.\1,我也可以在進入 command mode 後,輸入 s/ 後,按 ctrl+r,然後再按一下 /,那上一次打的 search pattern 就會出現了,這樣就省了不少力氣。
vim_replace_by_search_04

這就是結果了:
vim_replace_by_search_05

使用了 vim 這麼久,到現在才曉得怎麼輕鬆做到這件事 :p

comments powered by Disqus