简体   繁体   English

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

[英]vim backward search and replace before the matched pattern

I'm enjoying vim, and its powerful search and replace command.我很享受 vim 及其强大的搜索和替换命令。 However, I need to perform a complex research and substitute, like this one:但是,我需要进行复杂的研究和替代,如下所示:

1) find the first occurrence of "field.h" and delete the line 2) from the deleted line search backwards up to a line containing "foo.h" (this search has to be case insensitive), and put a new line just before it containing "include 'io.h'" 1) 找到第一次出现的 "field.h" 并删除第 2) 行,从删除的行搜索向后到包含 "foo.h" 的行(此搜索必须不区分大小写),然后添加一个新行在它包含“包括'io.h'”之前

3) repeat this operation for every occurrance of "field.h" in the file 3)对文件中每次出现“field.h”重复此操作

Now, I know how to delete all the lines in a file matching a pattern, and how to insert a new line before a pattern, but I don't knonw how to all of this combined.现在,我知道如何删除与模式匹配的文件中的所有行,以及如何在模式前插入新行,但我不知道如何将所有这些组合起来。

For point 1 above, I would do :g/field.h/d , while for point 2 something like :g/"foo.h"/s/#include "io.h"\\r&/g should work...对于上面的第 1 点,我会做:g/field.h/d ,而对于第 2 点,例如:g/"foo.h"/s/#include "io.h"\\r&/g应该可以工作...

As an example, the starting file could be:例如,起始文件可能是:

"foo.h"

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

and the resulting file should be:结果文件应该是:

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

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

Some can help me?有人可以帮我吗? Thanks谢谢

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

should work.应该管用。 Transforms变换

"foo.h"

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

"foo.h"

#include "FIELD.h"

into进入

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

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

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

Breaking it down:分解它:

  • :g/\\c"foo.h"/ : for all lines matching "foo.h" ( \\c for case-insentivity) :g/\\c"foo.h"/ : 对于所有匹配 "foo.h" 的行( \\c区分大小写)
  • d : delete d :删除
  • | : chain with another command : 与另一个命令链接
  • ?"foo.h"? : backward search for the previous "foo.h" : 向后搜索前一个"foo.h"
  • norm! : run the following input as in normal mode ( ! to remove all mappings, you might not need/want this) :在正常模式下运行以下输入( !要删除所有映射,您可能不需要/不想要这个)
  • O : Enter insert mode on the line above (do not use a - modifier to the search, it would fail to go above the first line) O : 在上一行进入插入模式(不要在搜索中使用-修饰符,它将无法在第一行之上)
  • #include "io.h" : write #include "io.h" #include "io.h" : 写 #include "io.h"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM