How to delete every other line in Vim?

前端 未结 12 1377
天涯浪人
天涯浪人 2020-12-04 06:13

I would like to delete every other line from a Vim buffer, starting with the second one, i.e., lines 2, 4, 6, etc. For example, if the buffer’s contents is:

a         


        
相关标签:
12条回答
  • 2020-12-04 06:47
    :%!awk -- '++c\%2'
    

    alternatively

    :%!awk -- 'c++\%2'
    

    depending on which half you want to weed out.

    0 讨论(0)
  • 2020-12-04 06:48

    You can use a macro for this. Do the following.

    • Start in command mode.
    • Go to the beginning of the file by pressing gg.
    • Press qq.
    • Click arrow down and press dd after.
    • Press q.
    • Press 10000@q

    PS: To go to command mode just press Escape a couple of times.

    0 讨论(0)
  • 2020-12-04 06:48
    :map ^o ddj^o
    ^o
    

    Here ^ stand for CTRL. Recursive macro to delete a line every two line. Choose well your first line and it's done.

    0 讨论(0)
  • 2020-12-04 06:53

    To delete odd lines (1,3,5,..) -> :%s/\(.*\)\n\(.*\)\n/\2\r/g

    To delete even lines(2,4,6,..) -> :%s/\(.*\)\n.*\n/\1\r/g

    Search for text (forms the first line) followed by a new line character and some more text (forms the second line) followed by another new line character and replace the above with either first match (odd line) or second match (even line) followed by carriage return.

    0 讨论(0)
  • 2020-12-04 06:55

    from vim mail archive:

    :let i=1 | while i <= line('$') | if (i % 2) | exe i . "delete" | endif | let i += 1 | endwhile
    

    (To be typed on one line on the vim command line, will delete row 1,3,5,7,...)

    0 讨论(0)
  • 2020-12-04 06:57

    As another approach you could also use python if your vim has support for it.

    :py import vim; cb = vim.current.buffer; b = cb[:]; cb[:] = b[::2]
    

    b = cb[:] temporarily copies all lines in the current buffer to b. b[::2] gets every second line from the buffer and assigns it to the whole current buffer cb[:]. The copy to b is necessary since buffer objects don't seem to support extended slice syntax.

    This is probably not the "vim way", but could be easier to remember if you know python.

    0 讨论(0)
提交回复
热议问题