2016-09-30 53 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