33

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

0

4 Answers 4

30

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

2
  • 11
    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. Commented Jan 14, 2016 at 18:21
  • 1
    @Carpetsmoker: This only works for letters in the current line. Commented Jul 28, 2017 at 6:43
17

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
1
  • 1
    Note that this solution only works if the <x> character is in the same line.
    – kazbeel
    Commented Mar 9, 2021 at 16:02
1
<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.

3
  • 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
    Commented Jul 26, 2017 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. Commented Jul 26, 2017 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
    Commented Jul 26, 2017 at 7:39
1

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 and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.