2016-09-30 52 views
1

我很享受vim及其強大的搜索和替換命令。但是,我需要執行一個複雜的研究和替代,如下所示:vim向後搜索並替換之前匹配的模式

1)找到第一個出現的「field.h」並刪除行 2)從刪除的行向後搜索直到包含「foo.h」(此搜索必須不區分大小寫),並在它包含「include」io.h之前放置一個新行。「

3)對每個」field.h「出現重複此操作在文件中

現在,我知道如何刪除匹配模式的文件中的所有行,以及如何在模式之前插入新行,但我不知道如何結合所有這些。

對於上述第1點,我會做:g/field.h/d,而對於第2點像:g/"foo.h"/s/#include "io.h"\r&/g應該工作...

舉個例子,啓動文件可能是:

"foo.h" 

lines of text, they can be also empty lines 
#include "field.h" 
other text 

所得文件應該是:

#include "io.h" 
"foo.h" 

lines of text, they can be also empty lines 
other text 

有人可以幫我嗎? 謝謝

+2

聽起來李關於vim宏的工作。如果你提供一個小樣本 – Amit

+0

是的,那麼它會有所幫助,添加一個前後示例。還要單獨添加你正在執行的命令,它會幫助別人使用它,甚至建議改進 – Sundeep

回答

1
:g/\c"field.h"/d | ?"foo.h"?norm! O#include "io.h" 

應該工作。變換

"foo.h" 

lines of text, they can be also empty lines 
#include "field.h" 
other text 

"foo.h" 

#include "FIELD.h" 

#include "io.h" 
"foo.h" 

lines of text, they can be also empty lines 
other text 

#include "io.h" 
"foo.h" 

其分解:

  • :g/\c"foo.h"/:匹配(用於區分insentivity \c) 「foo.h中」
  • d所有行:刪除
  • |:鏈與另一個命令
  • ?"foo.h"?:爲前"foo.h"
  • norm!向後搜索:運行下面的輸入在正常模式(!刪除所有映射,你可能不需要/想要這個)
  • O:上面的行中輸入插入模式(不使用-修改的搜索,它會失敗去第一線之上)
  • #include "io.h":寫的#include文件「io.h」
+0

太棒了!我剛剛意識到有時「foo.h」後面沒有#include「field.h」,但用這個命令不應該是個問題,不是嗎? – andrea

+0

那些''foo.h''''上面不會有'#include'io.h'',但我猜你想要什麼? – Marth

+1

這正是我想要做的。非常感謝。 – andrea