Bcpp
Bcpp

Reputation: 25

How to replace brackets with parentheses but keep contents between them?

I have the following string in vim:

if [ a == 100 ]

I want to change it to:

if (( a==100 ))

And I want to replace the bracket with parentheses and keep the content as they are, I try:

:%s/if \[ .* \]/if (( .* ))/g

and I got:

if (( .* ))

How can I just get the original content? Thank you guys in advance. :)

Upvotes: 2

Views: 861

Answers (3)

SergioAraujo
SergioAraujo

Reputation: 11790

Here a solution for situations (easier to read) where you have to perform the change not only in some lines but in dozens of them where the manual action becomes boring.

Using a macro:

let @a="f[r(f]r)"

f[ ................ jump to the [
r( ................ replace with (
f] ................ jump to ]
r) ................ replace with )

Jump to the line where the change is needed and type @a

Using a global command:

:g/if \[/normal f[r(f]r)
:g/if \[/normal @a

Basically we are using the same commands both in the macro and in the global command. notice that the seccond global uses the 'a' macro defined above.

Upvotes: 0

Walter
Walter

Reputation: 7981

Not to refute Rafael's answer, but as another, perhaps more general solution to working with surrounding character pairs: this is what Tim Pope's wonderful vim-surround plugin is for.

  1. Place cursor on or inside square brackets
  2. cs]) Change surrounding square brackets (]) to parentheses ())
  3. vi) Visually select inside parentheses ())
  4. S) Surround visual selection with parentheses ())

Step 2 changes your input to this:

if ( a == 100 )

And after step 4 it looks like this:

if (( a == 100 ))

Edit: Shortcut by @voger

Steps 3 and 4 can be combined into the quicker ysa)).

Upvotes: 6

Rafael
Rafael

Reputation: 7746

You can use:

%s/if \[\(.*\)\]/if ((\1))/

This uses backreferences, i.e, capturing what's between the meta-parenthesis and projects the captured content using \<number> according to the capture order.

You don't really need the g flag since shell scripts unlikely have multiple ifs on the same line.

Upvotes: 3

Related Questions