代码之家  ›  专栏  ›  技术社区  ›  John Topley

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

vim
  •  6
  • John Topley  · 技术社区  · 15 年前

    删除文本最有效的方法是什么 2010-04-07 14:25:50773调试这是调试日志语句- 从一个日志文件中,比如下面使用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 回复  |  直到 15 年前
        1
  •  13
  •   Joachim Sauer    15 年前

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

    编辑,解释:

    %: whole file
    s: subsitute
    .* - : find any text followed by a space a dash and a space.
    // : replace it with the empty string.
    
        2
  •  6
  •   sth    15 年前

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

    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
    
        3
  •  2
  •   Morfildur    15 年前

    我的解决方案是:

    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> 直到你完成,让自动钥匙重复做你的工作。

    注:
    尽管录制的宏不一定总是最快和最完美的工具,但它通常比查找更好的宏更容易录制和执行宏。

        4
  •  1
  •   Arda Xi    15 年前

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

        5
  •  0
  •   codaddict    15 年前

    你可以做到:

    1,$s/.*- //
    
    • 1 第1行
    • $ 最后一行
    • s 代换
    • .* 什么

    所以它在每一行上都替换了任何后面跟有连字符和空格的东西。

        6
  •  0
  •   Heikki Naski    15 年前

    :%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/.* - // 不起作用。

    regex的说明:

    .\{-} 匹配任何内容,不包括换行,尽可能少

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

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

    当然,如果行末所需值的格式不稳定,则不起作用,在这种情况下,如果行末所需值的长度相同或熟食店的长度相同,则其他解决方案也起作用。