1

Suppose, I have

abcd
efgh
ijkl
mnop
qrst

I want to delete the first 2 character of each even numbered line.

abcd
gh
ijkl
op
qrst
5

You can use sed to do this:

sed 'n;s/..//' file.txt > output.txt

Or inside of Vim via:

:%!sed 'n;s/..//'

A native solution in Vim can be accomplished with a sub-replace-expression

:%s/../\=line('.')%2==0?'':submatch(0)/

This works by replacing the first 2 character each line with either itself for odd lines or nothing for even lines.

For more help see:

:h :range!
:h :s
:h sub-replace-expression
:h line()
:h submatch()
1
  • 1
    +1 for the sed solution! BTW: :%!sed '2~2s/..//' (only GNU) Sep 6 '18 at 19:55
2

You can record a recursive macro and run it from the start of the file as macros stop when some action cannot be performed. In this case, it would be something like this:

qqqqqj$xxj@qq@q

Now, by parts:

qqq   -  Start and immediately end recording of register "q". This is only
         needed in recursive macros.

qq    -  Start recording in register q

j$xxj -  One line down, end of line, delete two characters and down again

@q    -  Run the contents of the macro @q (empty for now)

q     -  End recording of macro

@q    -  Run the contents of @q (not empty anymore)
2

Another native Vim command line solution:

:g/^../ if line(".") % 2 == 0 | s///

Pretty straightforward. The global command takes us to every line in the file that has at least two characters. Check modulo 2 of the current line number returned by line(".") and if it indicates an even line then substitute nothing for the first two characters. We don't have to specify a pattern with the substitution command as it defaults to the last search term, i.e. ^...

If you like compact this version is nice and short...about 10 chars shorter than the other native c/l solution posted here. ;)

:g/^../if line(".")%2==0|s///
0

My suggestion

:g/./if line('.') % 2 == 0 | normal! xx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.