Vim 删除从字符开始到行尾

问题描述 投票:0回答:8

我正在尝试想出一些方法来删除从给定字符开始到行尾的所有文本。

例如在下面的示例中,我只想保留 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
,即从左侧读取遇到的第一个“-”。文件中每一行从“-”到行尾都应删除。

我对这个问题感到困惑,将不胜感激。

vim
8个回答
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

22
投票

在普通模式下有一个简单的方法:

  1. /-m
    让光标移动到文件中第一个出现的“-m”。
  2. d$
    删除从光标处到行尾的字符。
  3. n
    找到另一个“-m”。
  4. .
    重做步骤 2。

9
投票

这不是很简单吗:

:%s/-m.*//

还是我没有理解这个问题?


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
    删除直至结束
  • +
    ,跳转到字符串开头的下一行,以便我们可以链接宏(
    l
    在vim上也应该工作,因为你删除到最后)

正如@Nobe4所说,您还可以在一行上注册宏(例如

qlt-Dq
),然后在视觉选择上重复:
VG:normal!@l


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

0
投票
  1. 将光标移至需要删除的行首。
  2. d
    键两次可删除线。

参考:https://alvinalexander.com/linux/vi-vim-delete-line-commands-to-end/


0
投票
shift-d

是另一种删除当前位置到行尾字符的方法。
其作用与

d$
相同。
从字面上看,“从当前位置到行尾,包括”。

© www.soinside.com 2019 - 2024. All rights reserved.