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
:%!awk -- '++c\%2'
alternatively
:%!awk -- 'c++\%2'
depending on which half you want to weed out.
You can use a macro for this. Do the following.
gg
.qq
.dd
after.q
.10000@q
PS: To go to command mode just press Escape a couple of times.
: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.
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.
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,...)
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.