12

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
.
.
7
  • 3
    how do you chose the rows to delete ? Do you wan to leave one row every 10 ?
    – matzeri
    Jul 16, 2016 at 5:50
  • 1
    You can delete ranges of lines with :[range]d for example :3,5d deletes lines three through five (inclusively).
    – Bratchley
    Jul 16, 2016 at 6:55
  • 6
    There is also vi.stackexchange.
    – Alexey
    Jul 16, 2016 at 9:00
  • @R Ketkaew - Are you trying to remove a list of numbers or are they rows? Could you please update your question to clarify ?
    – user14755
    Jul 16, 2016 at 11:43
  • I know you're asking about Vi, but you can do with GNU Sed, too: gsed -n '1p; 0~10p' Jul 16, 2016 at 15:47

2 Answers 2

17

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'
4
  • The awk command works for me. I always thought awk required a minimum of one block {...}. good to know you don't. It's the first non-trivial awk command I've got working! Jul 16, 2016 at 7:38
  • 1
    @the_velour_fog the block is required. if you don't write one, AWK will behave as if you had written { print $0 } Jul 16, 2016 at 15:41
  • @RKetkaew Which of the options did you use? If a response solves your question, please click on the tick to mark it as the answer. Jul 16, 2016 at 20:56
  • @underscore_d Hi, I used a command suggested from DarkHeart. Thank you for your comments. Jul 17, 2016 at 16:14
12
:2,$v/0$/d

deletes the lines that don't end in 0 starting from the second one.

1
  • 2
    This, this is the clever solution. I'd just add an explanation that 2,$ is the range, and v/0$/d the g! command. Where 0$ is the regex and d the ex command that will be run on all lines that do not match.
    – grochmal
    Jul 16, 2016 at 18:01

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.