如何使用 vim 上的正则表达式复制匹配块并写入另一个文件?

How to copy the matches block and write to another file using reqular expression on vim?

我的文件中有一组 code 块。我需要从该文件复制所有 code 块并写入另一个文件。

例如:

我当前的文件内容是:

CurrentFile.txt

* The method `make:` retrieves the prototype and clones it:

```cpp
make: partName
    ^ (partCatalog at: partName) copy
```

* The concrete factory has a method for adding parts to the catalog.

```cpp
    addPart: partTemplate named: partName
    partCatalog at: partName put: partTemplate
```

* Prototypes are added to the factory by identifying them with a symbol:

```cpp
    aFactory addPart: aPrototype named: #ACMEWidget
```    

从我当前的文件中,我只需要复制代码块并创建另一个文件,而无需更改我的当前文件。

预期的输出文件是

OutputFile.cpp

make: partName
    ^ (partCatalog at: partName) copy


    addPart: partTemplate named: partName
    partCatalog at: partName put: partTemplate


    aFactory addPart: aPrototype named: #ACMEWidget

为了匹配我的代码块,我在 vim 上使用了以下正则表达式 :%s/```cpp\n\(.*\n\)\{-}```//gc。请帮助解决我的问题。提前致谢...

可以结合使用pcregrep(因为普通的grep不支持多行匹配)

pcregrep -Mo1 '```cpp\n((.|\n)*?)```' input.cpp > output.cpp

上述命令将从名为 input.cpp 的文件中获取源代码,并将清理后的源代码写入名为 output.cpp.

的文件中

解释:

 //This matches the codeparts from your input file
 //whereby: -M is multiline, -o1 is first capturegroup => ((.|\n)*?)
 pcregrep -Mo1 '```cpp\n((.|\n)*?)```' input.cpp


 //This writes the cleaned text to output file
 > output.cpp

您可以通过命令写入范围

:g/^```cpp$/+1;/^```$/-1 w!>> filename

结果将与您在示例中所写的不完全相同,因为该示例包含源文件中不存在的额外空行。