3

I often find myself using something like:

sed -ri 's/<\/(abc|def ghi|j klm)>//g' someFile.html

to perform substitutions on multiple possible patterns, in this case, a closing html tag to be deleted, saving me the time and effort to do this three separate times for three closing tags I want deleted.

Is there a way to do this using substitute on vim's cli? I haven't yet found a way to do it, but it would be more efficient than going to a terminal cli or running sed from within vim if it could be done natively instead.

2 Answers 2

5

Yes, you don't need to use an external program at all:

:%s/<\/\(foo\|bar\|baz\)>//g

See :help :s, :help :range, and more generally :help pattern.

3
  • 1
    well don't I just feel stupid. I am sure I tried this command, except I must not have escaped the ORs | as the only thing I can see that I could have typed in wrong or omitted. Wierd. Oh well, good stuff to know.
    – ahchrist
    Aug 12, 2014 at 23:48
  • what is the '@' for?
    – splinux
    Mar 9 at 6:41
  • 1
    @splinux it's an alternative separator, generally used to avoid escaping slashes in the pattern. See :help pattern-delimiter, linked from :help :s. I have no idea why I used it here, though, because there's only one slash to escape. Let me make the answer less ambiguous.
    – romainl
    Mar 9 at 10:07
4

You can use the silent ! command to silently execute shell commands from inside vim:

:silent !sed -ri 's/<\/(abc|def ghi|j klm)>//g' %

This will execute the command in the shell silently (it won't take you away from vim to see any shell output). The % means the current buffer name. Vim will then notify you that the file you are editing has been changed and will ask you if you want to load the changes, press l for load and the new changes from the sed shell command will appear.

1
  • 1
    although romainl answered my question, +1 for a great additional answer. I avoid using sed on the vim cli b/c exactly b/c as you describe it takes you away from vim to view shell output. So I will be tying that :silent option to a shortcut and using sed a little more often within vim I think.
    – ahchrist
    Aug 12, 2014 at 21:13

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.