Polb
Polb

Reputation: 700

Ways to delete a line in vim

I need to delete several lines in vim (line 42,line 424 and line 4242). I found 2 possible solutions:

However, to get the task done, I have to delete all the 3 lines. Should I do something like this? :42d :423d :4240d

Or this?

:4242d :424d :42d

Once I do this, I need to replace the 42nd occurrence of a word with another word (replace "Vader" with "Vader(father figure)"). I looked for "Vader" by typing 42/Vader, then entered the 'INSERT' mode and replaced the word. The problem I encounter here is that a checker is telling me that the original file does not contain the correct information. I think there is a problem with the lines deletion. Or am I failing to replace "Vader" with "Vader(father figure)" ?

Upvotes: 0

Views: 141

Answers (2)

romainl
romainl

Reputation: 196476

The first task could be done with:

:4242dd|424d|42d<CR>

or:

4242Gdd424G.42G.

Note the reverse order, necessary for maintaining line numbering throughout the task.


gg42/Vader<CR>

is a safer way to search for the 42nd occurrence of Vader because it starts at the top of the buffer.

Once your cursor is on the right Vader, you can do:

cgnVader(father figure)<Esc>

to replace it.

You can use the unnamed register to avoid re-typing Vader:

cgn<C-r>"(father figure)<Esc>

But it's probably better to make your search land on the last character of your match:

/Vader/e<CR>
a(father figure)<Esc>

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172510

If you really start with the line numbers, I would delete from end to start, to avoid offset calculation. You can concatenate all :delete commands in a single command-line:

:4242d|424d|42d

By the way, you don't need Vim for that; a scripted solution can be done with Unix tools like sed -i -e 4242d -e 424d -e 42d.

But far more often, you don't start with line numbers, but instead navigate to the lines, e.g. by search. Then, the usual sequence is dd (delete current line), n (go to next match), . (repeat).

Upvotes: 2

Related Questions