Vi editor: What’s the fastest way to delete multiple rows in a file

vivim

I'd like to use the Vi editor to delete multiple rows in a file. Please give me idea or suggestion.

My goal is like this:

Before:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.
.
29
30
.
.

After;

1
10
20
30
40
.
.

Best Answer

If you mean you want to keep every 10th line and delete the rest:

%norm 9ddj

Explanation:

% whole file

norm execute the following commands in "normal mode"

9dd delete 9 lines

j move down one line (i.e. keep it)

note: this deletes the first row.

Adapted from http://www.rayninfo.co.uk/vimtips.html


Or using the global command:

  • Duplicate the first line ggYP
  • :g/^/+ d9

Adapted from https://stackoverflow.com/questions/1946738/vim-how-to-delete-every-second-row


Or you could use awk:

%!awk 'NR \% 10 == 0 || NR == 1'
Related Question