I have the text pattern [2]
in a text file. I want to replace it with the text string [1]
.
Using this command:
:%s/\<[2]\>/[1]/
Vim only replaces the string '2' in the square brackets so the result is [[1]]
.
I read that when searching:
After an opening [, everything until the next closing ] specifies a /collection source.
So I tried escaping the square brackets:
:%s/\<\[2\]\>/[1]/
But I received this error:
E486: Pattern not found: \<\[2\]\>
Enclosing the entire pattern in the brackets (:%s/\<[[2]]\>/[1]/
) also returns the E486: Pattern not found: \<[[2]]\>
error
Then removing the special character (or more accurately escape sequence) for the beginning of a word ('<') and the end of a word ('>') i.e. :%s/[[2]]/[1]/
gives the result [[1]
.
- When searching with the
:s
(substitute) command, the collection[[2]]
should match any single character '[', '2' or ']', so why does:%s/\<[[2]]\>/[1]/
cause anE486: Pattern not found: \<[[2]]\>
error? - How do you search for text patterns consisting of an opening bracket (
[
) and closing bracket (]
) e.g. the text pattern[2]
? - Why is
[ ]
interpreted as a collection in the search part of the substitute command, but[ ]
is not interpreted as a collection in the replace part of the substitute command? - Why does
:%s/[[2]]/[1]/
only replace the text pattern '2]' i.e. giving the result[[1]
? - Does enclosing the entire pattern in the brackets (
:%s/\<[[2]]\>/[1]/
) return anE486: Pattern not found: \<[[2]]\> error
because Vim tries looking for the text pattern '[[2]]' but couldn't find it, or is something else causing this error? - The command
:%s/\<[2]\>/[1]/
only replaces the string2
in the square brackets (the result is[[1]]
), which indicates that the collection[2]
matches only the single character2
, but what happened to the beginning-of-a-word escape sequence ('<') and the ending-of-a-word escape sequence ('>')? Why do the escape sequences have no effect or not cause an error?