regex - 删除除模式和下一行 vim 之外的所有内容

标签 regex vim

尝试找出如何使用正则表达式功能从 vim 中删除除模式之外的所有内容。

具体来说,我正在尝试删除除“United States”行以及紧随其后的行(来自 Arch Linux Mirrorlist)之外的所有内容。 所以这...

## Austria
Server = http://mirror.easyname.at/archlinux/$repo/os/$arch
## United States
Server = http://mirror.cs.pitt.edu/archlinux/$repo/os/$arch
## Thailand
Server = http://mirror2.totbb.net/archlinux/$repo/os/$arch

应该转换成这个...(并对美国线的每个实例继续这个)

## United States
Server = http://mirror.cs.pitt.edu/archlinux/$repo/os/$arch

我尝试用来完成此操作的行是:

:v/## United States\n\_.\{-}\_$/d

如果我理解正确的话,:v 选择除模式之外的所有内容。我试图输入的模式是美国行加上下一行 (\n) 以及之后到行尾的所有内容 (\_.\{-}\_$),然后删除所有这些垃圾(/d)。

但是,当执行该行时,我只得到与美国相关的行。像这样的事情:

## United States
## United States
## United States
...

如何保存美国线之后的线?

最佳答案

If I understand correctly, :v selects everything but the pattern. The pattern I'm trying to feed it is the United States line plus the next line (\n) and everything after that to the end of the line (\_.\{-}\_$) and then delete all this junk (/d).

关闭。但也不完全是。有一个微妙的区别。 :v (或 :g! )将在与正则表达式不匹配的每一行上运行特定命令。这真的非常接近你想要的,只是不完全在那里。问题就在这里。该行:

## United States

确实匹配您的正则表达式,这是真的。因此,这一行不会被删除。但是,紧随其后的行将被测试,并且

Server = http://mirror.cs.pitt.edu/archlinux/$repo/os/$arch

与您的正则表达式不匹配。所以它确实被删除了。

我能想到的最简单的解决方案是匹配每个位置行(因此您的行以 ## <location > 开头)除了 ## United States 之外 ,然后对于每个匹配项,删除该行和以下行。例如:

:g/## \(United States\)\@!/,+1d

关于regex - 删除除模式和下一行 vim 之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100580/

相关文章:

vim - Windows中的VIM编译

reactjs - 任何 VIM 插件都可以帮助我重构 React 组件吗?

linux - .vim/: No such file or directory

linux - vim 中的可视化 block 编辑

Python:正则表达式搜索

python - 如何将两个 url 组合为正则表达式模式

python - 将复杂的 str 更改为 pandas Dataframe 中的 float

C# 排序并放回 Regex.matches

mySQL - 在一个字段中查找大量关键字的上下文

regex - 在 vim 上使用正则表达式查找并将所有 href 链接内容替换为 '#' ?