In vim we have the :substitute command that searches for a text pattern and replaces it with a text string.

How does one handle a text pattern with punctuation in it?

Minimum working example: the text pattern $S(\R^2)$ has to be replaced with the text string $\Sm$. Edit: How do we also account for the fact that the text pattern can be inside another text pattern?

  • Are you talking about these kind of substitutions? :s/S(\\R^2)/\\Sm/ – NigoroJr Mar 16 '14 at 17:56
  • 1
    Yes. So \\ signifies a backslash? Are parentheses inserted without any adjustment? By the way, I changed my MWE. Your solution did not work on the changed MWE. – Mussé Redi Mar 16 '14 at 18:02
  • 1
    Take a look at Vim's :help pattern.txt and :help sub-replace-special to see how special characters are represented in search patterns and replacement strings. – garyjohn Mar 16 '14 at 18:21

It looks like it's a matter of escaping the characters. For your example,


will replace the first occurrence of S(\N^2) with \Sm. \\ is escaping \ (just like you do \* when you want to represent the character *). Without that, for example, the string \r will mean carriage return. The reason why you don't have to escape the $ in the second part of :s (don't know the technical term for it) is because it doesn't have any special meaning to it whereas it means the end of line in the first part.

You need to add backslashes to parentheses only when you want to capture.

  • We need to also account for the fact that the text pattern can be inside another text pattern. I understand that one can do this by preceding the text pattern with \< and closing it with \>. Only, this did not work. Any suggestions? – Mussé Redi Mar 16 '14 at 19:23
  • Can you give an example for that? \< and \> match the beginning/end of the word (refer to :h \<) – NigoroJr Mar 16 '14 at 19:48
  • For example $S(R^2)$,, where there is also a comma but we only want to replace the text pattern excluding the comma. – Mussé Redi Mar 16 '14 at 19:54
  • The command I gave does that. If you want to replace all occurrences, add the g modifier at the end. For example, :s/foo/bar/g will replace all foos in the current line with bar. – NigoroJr Mar 16 '14 at 19:59
  • Adding a % was what I needed, in order to replace all such occurances in the whole file. So we have :%s/\$S(\\R^2)\$/$\\Sm$/. – Mussé Redi Mar 16 '14 at 20:05

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.