我正在尝试想出一些方法来删除从给定字符开始到行尾的所有文本。
例如在下面的示例中,我只想保留 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
,即从左侧读取遇到的第一个“-”。文件中每一行从“-”到行尾都应删除。
我对这个问题感到困惑,将不胜感激。
全局命令是一个不错的选择
: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
在普通模式下有一个简单的方法:
/-m
让光标移动到文件中第一个出现的“-m”。d$
删除从光标处到行尾的字符。n
找到另一个“-m”。.
重做步骤 2。这不是很简单吗:
:%s/-m.*//
?
还是我没有理解这个问题?
我会做:
:%norm f D
“在每一行上,将光标移动到第一个空格,然后剪切从光标到行尾的所有内容。”
:help range
:help :normal
:help f
:help D
我会注册一个宏,例如:
0
ql
开始在字母上注册宏l
t-D+
q
结束宏3@l
启动三次t-D+
的解释:
t-
位于下一次出现的 -
D
删除直至结束+
,跳转到字符串开头的下一行,以便我们可以链接宏(l
在vim上也应该工作,因为你删除到最后)正如@Nobe4所说,您还可以在一行上注册宏(例如
qlt-Dq
),然后在视觉选择上重复:VG:normal!@l
。
使用视觉模式选择文本,然后使用:
:'<,'>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
d
键两次可删除线。参考:https://alvinalexander.com/linux/vi-vim-delete-line-commands-to-end/
shift-d
是另一种删除当前位置到行尾字符的方法。
其作用与
d$
相同。