使用Vim重复删除前导文本的最有效方法是什么?

时间:2010-04-07 13:53:39

标签: vim

删除文本的最有效方法 2010-04-07 14:25:50,773 DEBUG这是一个调试日志语句 - 来自日志文件,如下面的摘录使用Vim?

2010-04-07 14:25:50,772 DEBUG This is a debug log statement - 9,8
2010-04-07 14:25:50,772 DEBUG This is a debug log statement - 1,11
2010-04-07 14:25:50,772 DEBUG This is a debug log statement - 5,2
2010-04-07 14:25:50,772 DEBUG This is a debug log statement - 8,4

这就是结果应该是这样的:

9,8
1,11
5,2
8,4

请注意,在这种情况下我在Windows上使用gVim,所以请不要建议任何可能更适合该任务的UNIX程序 - 我必须使用Vim。

6 个答案:

答案 0 :(得分:13)

运行命令::%s/.* - //

编辑,解释:

%: whole file
s: subsitute
.* - : find any text followed by a space a dash and a space.
// : replace it with the empty string.

答案 1 :(得分:6)

您还可以使用视觉块模式选择要删除的所有字符:

gg        Go to the beginning of the file
Ctrl-v    Enter visual block mode
G         Go to the end of the file
f-        Go to dash
<right>   Go one more to the right
d         Delete the selected block

答案 2 :(得分:2)

我的解决方案是:

qa                 [start recording in record buffer a]
^ (possibly twice) [get to the beginning of the line]
d3f-               [delete everything till - including]
<del>              [delete the remaining space]
<down>             [move to next line]
q                  [end recording]
<at>a              [execute recorded command]

然后按住<at>直到完成为止,让自动键重复为您完成工作。

注意:
尽管记录的宏可能并不总是最快和最完美的工具,但通常更容易记录和执行宏而不是更好地查找。

答案 3 :(得分:1)

最简单的方法可能是使用宏。按qa开始注册a中的录制。然后按照您在Vim中习惯的方式删除字符。按q停止录制。然后,取出行数并附加@a,例如4,按4@a。这将重复宏4次。

答案 4 :(得分:0)

你可以这样做:

1,$s/.*- //
  • 1:第1行
  • $:最后一行
  • s:替换
  • .*:任何

所以它取代了每一行,后面跟着连字符和空格,没有任何内容。

答案 5 :(得分:0)

:%s/.\{-}\ze\d\+,\d\+$//

该命令通过锚定到行尾的逗号分隔数字起作用,因此即使除了字符串中的那些数字之外的其他所有内容都会更改,它也能正常工作。

视觉阻止方式可能是最简单的解决方案,也是我使用的解决方案。但是,如果线条变得交错,它就不起作用,如:

2010-04-07 14:25:50,772 DEBUG This is a debug log statement - 9,8
2010-04-07 14:25:50,772 DEBUG This is another debug log statement - 9,8

分隔符也可能会更改为不同的字符,因此行如下所示:

2010-04-07 14:25:50,772 DEBUG This is a debug log statement | 9,8

然后使用:%s/.* - //将无效。

正则表达式的解释:

.\{-}尽可能少地匹配排除换行符的内容

\ze停止匹配,因此替换不会影响以下字符

\d\+,\d\+$个数字,至少一个,后跟一个逗号,后跟数字,至少一个,行尾

当然,如果行尾的所需值的格式不稳定,则它不起作用,在这种情况下,如果到达值的行具有相同的长度或者分隔符相同,则其他解决方案可以工作。

相关问题