11

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
.
.
  • 3
    how do you chose the rows to delete ? Do you wan to leave one row every 10 ? – matzeri Jul 16 '16 at 5:50
  • You can delete ranges of lines with :[range]d for example :3,5d deletes lines three through five (inclusively). – Bratchley Jul 16 '16 at 6:55
  • 5
    There is also vi.stackexchange. – Alexey Jul 16 '16 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 ? – DarkHeart Jul 16 '16 at 11:43
  • I know you're asking about Vi, but you can do with GNU Sed, too: gsed -n '1p; 0~10p' – shadowtalker Jul 16 '16 at 15:47
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'
  • 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! – the_velour_fog Jul 16 '16 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 } – shadowtalker Jul 16 '16 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. – underscore_d Jul 16 '16 at 20:56
  • @underscore_d Hi, I used a command suggested from DarkHeart. Thank you for your comments. – rangsiman Jul 17 '16 at 16:14
12
:2,$v/0$/d

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

  • 1
    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 '16 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.