vim在匹配模式之前向后搜索和替换

时间:2016-09-30 15:35:06

标签: 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
有些人可以帮助我吗? 感谢

1 个答案:

答案 0 :(得分: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"/:对于匹配" foo.h" (\c用于不区分大小写)
  • d:删除
  • |:使用其他命令链
  • ?"foo.h"?:向后搜索上一个"foo.h"
  • norm!:在正常模式下运行以下输入(!以删除所有映射,您可能不需要/想要这样)
  • O:在上面一行输入插入模式(不要在搜索中使用-修饰符,它将无法超越第一行)
  • #include "io.h":写#include" io.h"