搜索和删除多行 [英] Search and delete multiple lines

查看:34
本文介绍了搜索和删除多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在vim中

:g/乔治·布什/d

删除所有带有 George Bush 的行.

如果我想删除下面以 George Bush 开头的 5 行怎么办?

What if I wanted to delete 5 lines below that start with George Bush?

另一个现实的例子是在 log4net 日志中找到所有 DEBUG 并删除直到堆栈跟踪的末尾(我知道它下面还有 10 行)

Another realistic example would be to find all DEBUG in a log4net log and delete up to the end of stack trace (which I know will be another 10 lines below it)

推荐答案

:global 命令是您的朋友 - 好好学习.它允许您在匹配正则表达式的每一行上运行任意 :ex 命令.它缩写为:g.

The :global command is your friend - learn it well. It lets you run arbitrary :ex commands on every line that matches a regex. It abbreviates to :g.

删除所有匹配George Bush"的行:

To delete all lines that match "George Bush":

:g/George Bush/ d

后面的命令可以有自己的地址/范围前缀,这将相对于匹配的行.所以要删除 George Bush 之后的第 5 行:

The command that follows can have its own address/range prefix, which will be relative to the matched line. So to delete the 5th line after George Bush:

:g/George Bush/ .+5 d

要删除调试日志条目:

:g/DEBUG/ .,+10 d

如果您知道堆栈跟踪是可变长度的,但总是以空行(或其他正则表达式)结尾:

If you knew the stack trace was variable length but always ended at a blank line (or other regex):

:g/DEBUG/ .,/^$/ d

您还可以在不与 :g! 匹配的每一行上执行命令.例如在不包含sucks"一词的每一行中将Bush"替换为Obama":

You can also execute a command on every line that does NOT match with :g!. e.g. to replace "Bush" with "Obama" on every line that does not contain the word "sucks":

 :g!/sucks/ s/Bush/Obama/

默认命令是将行打印到消息窗口.例如列出标记为 TODO 的每一行:

The default command is to print the line to the message window. e.g. to list every line marked TODO:

 :g/TODO

这对于在执行破坏性操作之前检查正则表达式是否与您期望的行匹配也很有用.

This is also useful for checking the regex matches the lines you expect before you do something destructive.

您可以使用|"链接多个命令.例如在不包含sucks"的每一行将布什改为奥巴马,将乔治改为巴拉克:

You can chain multiple commands using "|". e.g. to change Bush to Obama AND George to Barack on every line that does not contain "sucks":

 :g!/sucks/ s/Bush/Obama/g | s/George/Barack/g

这篇关于搜索和删除多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆