Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep only the 1st line in every 4 lines and delete the other lines [duplicate]

Tags:

vim

I have a file like the following

a
b
c
d
e
f
g
h
i
j
k

and I want it to be:

a
e
i

How to do it in vim?

like image 575
Qiang Li Avatar asked Jun 23 '13 07:06

Qiang Li


2 Answers

You can do that with the following key sequence:

gg
qa
j
3dd
q
999@a

This is what the commands mean:

gg      # jump to the beginning of the file
qa      # start recording a macro in register "a"
j       # move down 1 line
3dd     # delete 3 lines (including the current one)
q       # stop recording the macro
999@a   # replay the macro from register "a"

If you have sed in your system (you are in Linux, Mac OS X, or using Git Bash in windows), then it's cleaner to do this instead:

:%!sed -ne 1~4p

This filters the content of the entire buffer, sending it to sed over a pipe, and then the sed command prints every 4th line of the input starting from line 1.

like image 83
janos Avatar answered Nov 09 '22 14:11

janos


Adapted from an answer to another similar question.

:g/^/+1 d3

(you don't need the spaces, I just added them for clarity)

  • /^/ matches any line.
  • :d can take a numeric argument which specifies how many lines to delete including current line.

So the command translates to: for every line that comes after another line, delete 3 lines including the current line.

Another interpretation would be: for every line, delete the next 3 lines.

like image 28
doubleDown Avatar answered Nov 09 '22 13:11

doubleDown