13

If I want to delete every word, that is easy, because I would do something like this:

:s%/WORD//g

But what if I want to do xyz to every occurrence of "WORD"? For example, let's say I want to delete every line that contains "WORD". I can think of a couple ways to do this, but none of them seem ideal.

1)

/WORD

and then manually press ddnddnddnddn... until there are no more occurrences. But this is time consuming if there are many lines to do this on.

2)

qd/WORD<enter>ddq

and then guess how many times WORD occurs, and then, for example:

500@d 

But this will either A) miss a bunch of lines or B) delete of bunch of extra lines.

Is there a better way to do this?

  • 3
    Just so you know, 500@d as you describe is actually safe. The macro playback will stop once the search term is not found. So you'll just see an error "Pattern not found: WORD" after all lines containing it have been deleted. – Wildcard Oct 13 '15 at 18:01
  • @Wildcard Thankyou, that is really good to know! – DJMcMayhem Oct 13 '15 at 18:15
17

You can use the :global and :normal commands for this. The :global command has the following syntax:

:global/{pattern}/{command}

This will run "command" on every occurrence of "pattern". You can then use the :normal command to run a series of keystrokes on each occurrence of a word using :global. Like so:

:g/WORD/normal {keystrokes}

If those keystrokes involve special keys like <Ctrl>, you can combine it with the :execute command like so:

:g/WORD/exe "normal {keystrokes}"

Do note that you must put a backslash before each occurrence of a special key.

For more on these commands, see :help :normal and :help :global.

  • Beat me to it; I guess I was typing too slow. :) – Wildcard Oct 13 '15 at 17:57
3

Just for completeness, you can use :substitute, if you match - in your example (delete the whole line that has WORD) - the entire line containing WORD, e.g.:

:%s/^.*\<WORD\>.*\n

This has an implicit "replace match with nothing", i.e. it's the shorter form of:

:%s/^.*\<WORD\>.*\n//

Combined with \zs, \ze, \(-\) (grouping), and \= (in the replacement part) with submatch(), :substitute can be very powerful.

2

It seems you are looking for :global.

:g/WORD/d_
  • What does the underscore do? – Wildcard Oct 13 '15 at 17:48
  • This works, but none of the commands I know work. I keep getting "not an editor command". – DJMcMayhem Oct 13 '15 at 17:56
  • 1
    @Wildcard: The underscore discards what is being cut. The command executed is actually :delete and not the normal mode operation d. – Luc Hermitte Oct 14 '15 at 7:22
  • @DJMcMayhem: for other normal operations, you'll need :normal. And if you need special keys, you may even need :exe -> `exe "normal aFooFar\<esc>" – Luc Hermitte Oct 14 '15 at 7:24

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.