'VIM Search and replace contents between square brackets

I need to replace contents in square bracket with \ while preserving the contents in the bracket.

eg : string

[.\*][.\*][.\*]

to be replaced with string

\\[.\*\\]\\[.\*\\][.*]

Given the following line :

abcdef[0][box][21] 

I need to replace it with

abcdef\\[0\\]\\[box\\][21]


Solution 1:[1]

VIM command search and replace all occurrence of [ ] to \[ \]:

syntax: %s/pattern/replacement/flags

Command

:%s/\(\[\|\]\)/\\\1/g

Pattern Explanation

:%s makes it work on the whole file, rather than just the current line.

\(\[\|\]\) :

  • \( starting of group
  • \[ escaped opening square bracket
  • \| OR operator
  • \] escaped closing square bracket
  • \) end of pattern group

\\\1 : Replace previous captured group with \[ or \]

/g: Replace all occurrences in the line

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gajendragarg