14

I know that I can delete from the cursor till and including the first occurence of a character x with d/x<CR> or with v/x<CR>d if I want to see the selection first and then delete. How can I delete from the current cursor position till the nth occurence of x?

E.g., if the cursor is after the first space in

yada yada yada
yada yada yada x
yada yada yada x
yada yada yada x

xx

and I type a command to remove up to the third x the result needs to be:

yada
xx

20

You can do :

wd4/x<Enter>

If you start on the top left of your text

Explanation

  • w : move to beginning of next word
  • d : delete
  • 4/x<Enter> : until the 4th occurence of x

If you don't know the number of times you would like to do it beforehand, you can also do : d/x<Enter> and then hit . to repeat

  • 5
    Bonus tip: This also works with f and friends (F, t, T, ;): e.g. 2fx will get you to the second x, or 2; will repeat the last f twice. – Martin Tournoij Jan 14 '16 at 18:21
  • 1
    @Carpetsmoker: This only works for letters in the current line. – Jürgen Krämer Jul 28 '17 at 6:43
4

You can do this by typing

<n>df<x>

where:

<n> is the number of occurrence of particular character
df<x> means delete till you find the occurrence of character x
0
<n>macro 

is commonly used in vim to repeat the macro "n" times.

so in order to delete till 1st occurrence of x, you would use 1dfx. Similarly, to delete till the 3rd occurrence of x, you would use 3dfx.

  • 1
    I think you missued the word "macro": in vim a macro is a sequence of key recorded in a register and call with @x where x is your register. What you are referring to is a normal mode command. – statox Jul 26 '17 at 7:31
  • Yes I meant a normal command. But this is true for a macro as well. We can run the macro n times by adding a number before the macro. – thenakulchawla Jul 26 '17 at 7:33
  • 1
    Yes that's true. I was just pointing out that <n>macro isn't a standard notation in vim for the macros and as your answer uses a normal mode command it is pretty much the same as kapil's one. – statox Jul 26 '17 at 7:39
0

Given:

yada yada yada$
yada yada yada x$
yada yada yada x$
yada yada yada x$
xx$

where the $ indicate ends of lines (:set list mode), if the cursor is at the start of second yada in the first line, first we have to back up to the preceding space using h, to include it in the deletion. Then just 4d/xEnter. In other words, just a count in front of d/x. The result is exactly:

yada$
xx$

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.