I have the text pattern [2]
in a text file. I want to replace it with the text string '[1]'.
Using the command:
:%s/\<[2]\>/[1]/
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 got the error:
E486: Pattern not found: \<\[2\]\>
Enclosing the entire pattern in the brackets (:%s/\<[[2]]\>/[1]/
) also returns an E486: Pattern not found: \<[[2]]\>
error
Then removing the special character (or more accurately escape sequence) for beginning of a word ('\<') and 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 pattern consisting of an opening bracket ('[') and closing bracket (']') e.g. the text pattern '[2]'?
- How come [ ] 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
becausevim
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 string '2' in the square brackets ( the result is[[1]]
) which indicates that the collection [2] matches only the single character '2' but what happened to the begin of a word escape sequence ('\<') and end of a word escape sequence ('>')? Why do the escape sequences have no effect or not cause an error?