Search code examples
regexvim

vim: Selectively replacing brackets in a file


I have following text file:

A(B C)
D(E F)
A(G 
H 
I)

I want to convert this to:

modifiedA{B C}
D(E F)
modifiedA{G 
H
I}

Usually, I would use s/A(/modifiedA\{/g and s/)/}/g.

Since I don't want to touch the line with D(E F), this won't work.

Thank you for your comments/help.

Update:

  1. The answer should not require human intervention and should be scalable. Hence, using c instead of g is not an option.

  2. Also note that A() can be spread across multiple lines.


Solution

  • In order to match a multiline pattern we need \_.\{-} which means non-greedy regex search:

    :%s/\(A\)(\(\_.\{-}\))/modified\1{\2}
    
    \( ................ start of a regex group
    \) ................ end of a regex group
    \_.\{-} ........... non-greedy regex
    \1 ................ back reference to the regex group 1
    

    Using very magic option see :h \v.

    %s/\v(A)\((\w \_.{-})\)/modified\1{\2}