从特定字符开始删除至行末的Vim命令

14

我正在尝试设计一种方法,可以从给定字符开始删除至行末的所有文本。

例如,在下面的示例中,我只想保留IP地址:

192.168.2.121/32 -m comment --comment "blah blah bye bye"  -j DROP
10.1.3.207 -m comment --comment "much longer comment with all kinds of stuff" -j DROP
172.16.1.0/24 -m comment --comment "Drop this range" -j DROP

需要删除的模式是-m,即从左侧开始阅读,遇到第一个"-"。从该符号到行末的内容应在文件的每一行上被删除。

我对这个有困惑,希望能得到指导。

7个回答

28
一个全局命令将是一个很好的选择。
:g/-/norm nD

解释

:g         : Start a Global Command (:h :g for extra help on global commands)
/-         : Search for -
/norm nD   : Execute nD in Normal Mode where 
               n - jumps to the match
               D - delete to the end of the line

有没有全局命令可以从行首删除到给定字符? - anishjp
2
@anishjp - 是的,请尝试 %norm 0dt<character> - Lieven Keersmaekers
谢谢您。如果我还需要删除给定的字符呢? - anishjp
1
@anishjp - %norm 0df<character> - Lieven Keersmaekers

21

在正常模式下,有一种简单的方法可以做到这一点:

  1. /-m 让光标移动到文件中第一个出现 "-m" 的位置。
  2. 按下 d$ 删除从光标到行尾的字符。
  3. 按下 n 查找下一个 "-m"。
  4. 按下 . 重复步骤2。

按下d$以删除光标到行尾的字符。这正是我在寻找的,谢谢。 - Asmoox

9
这难道不是很简单吗:

:%s/-m.*//

或者我没有正确理解问题?


1
在这种情况下,%s/ .*// 也可以。 - Luc Hermitte
@LucHermitte 确定这对 OP 的示例数据有效。但是他的要求来自“-m”。因此,我会遵循 OP 说的,而不是示例。否则,它可能就像 :%norm! WD 一样简单。 - Kent
不,这并不简单。它一点也不简单。 - kmonsoor

2
我会做以下事情:
:%norm f D

在每一行中,将光标移动到第一个空格并将光标后的所有内容剪切掉。

:help range
:help :normal
:help f
:help D

1
我会注册宏,例如:
  1. 将光标放在第一行,位置为0
  2. ql在字母l上开始注册宏
  3. t-D+
  4. q结束宏
  5. 启动宏,可以多次运行,例如:3@l运行三次
t-D+的解释:
  • t-移到下一个-前面
  • D删除到末尾
  • +跳转到下一行字符串的开头,以便我们可以链接宏(在vim中,l也应该能用,因为你已经删除到末尾)
正如@Nobe4所说,您也可以在一行上注册宏(例如qlt-Dq),然后在可视选择上重复使用:VG:normal!@l

如果您有一个逐行操作的宏,您可以使用 :'<,'>normal! @q 在一系列行上重复它,这也可能很有用 :) - nobe4
'<,'> 是视觉选择吧?顺便说一下,它对我不起作用。 - soyuka
你是否尝试过在结尾删除 j0 以运行宏?为了实现这个,你可以使用 v 选择一组代码行,然后按下 : 键,应该会出现 :'<,'> - nobe4
1
我的错,我用了错误的字母(你打了 q 我这里用了 l ;))。谢谢你的提示,我会改进我的回答。为什么使用 % 作为缓冲区而不是可视选择不起作用? - soyuka
1
两个注释:1)d$ 可以改为 D 2)j0 可以改为 + - Kent

0

0

使用可视化模式选择您的文本,然后使用:

:'<,'>s/\([^- ]*\).*/\1/

分解:

:'<,'>s/     " start a substitution on current selected lines
\([^- ]*\)   " capture a groupe of everything except a space and a -
.*/          " match the rest of the line
\1/          " replace by only the matched group

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接