Suppose, I have


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


4 Answers 4


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


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 for the sed solution! BTW: :%!sed '2~2s/..//' (only GNU) Sep 6, 2018 at 19:55

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///

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:


Edit: Should use ^ instead of $ to delete from the start of line.

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)
  • 1
    A small correction - The question asked to delete the first 2 characters. For this, we need to replace the $ (line-end character) with ^ (line-start character). We can also leave out the ^ character altogether, coz the cursor is already at the line-start in the beginning as well as when it goes one line down each time. So we can use qqqqqj^xxj@qq@q orqqqqqjxxj@qq@q. Oct 28, 2021 at 11:31

My suggestion

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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