Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one escape backslashes and forward slashes in VIM find/search?

Tags:

regex

vim

For instance, if I wanted to a find and replace with strings containing backward or forward slashes, how would this be accomplished in vim? Thank you!

Examples Find & Replace is: :%s/foo/bar/g

what if I wanted to find all occurrences of <dog/> and replace it with <cat\>

like image 682
stormist Avatar asked Mar 17 '10 19:03

stormist


People also ask

How do I find slashes in Vim?

Basic Search To go back to normal mode from any other mode, just press the Esc key. Vim allows you to quickly find text using the / (forward slash) and ? (question mark) commands. It is important to note that the search command looks for the pattern as a string, not a whole word.

How do I escape a character in Vim?

To escape a special character, precede it with a backslash ( \ ). For example, to search for the string “anything?” type /anything\? and press Return.

How do you escape a forward slash?

In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$} , which may read more clearly).

How do you escape a slash in grep?

To search for a backslash character itself, double it \\ so that its first appearance will escape the second. For example, perhaps the most common "special character" in grep is the dot: ".". In grep, a dot character will match any character except a return.


1 Answers

Same way you escape characters most anywhere else in linuxy programs, with a backslash:

:%s/<dog\/>/<cat\\> 

But note that you can select a different delimiter instead:

:%s@<doc/>@<cat\\>@ 

This saves you all typing all those time-consuming, confusing backslashes in patterns with a ton of slashes.

From the documentation:

Instead of the / which surrounds the pattern and replacement string, you can use any other single-byte character, but not an alphanumeric character, \, " or |. This is useful if you want to include a / in the search pattern or replacement string.

like image 59
Cascabel Avatar answered Sep 18 '22 13:09

Cascabel