Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing brackets

Tags:

regex

vim

sed

awk

I would like to replace all occurrences of "exp( ... )" with "Exp[ ... ]" in the following (essentially changing from Matlab to Mathematica syntax):

exp(-(pi*k2*2i)/3)*(v9/4 + (3^(1/2)*(v8/2 + (3^(1/2)*v9)/2))/2 + (3^(1/2)*v8)/12) + exp((pi*k2*2i)/3)*(v9/4 + (3^(1/2)*(v8/2 + (3^(1/2)*v9)/2))/2 + (3^(1/2)*v8)/12) ...

Is it possible to automate this with vim, sed, or awk? The trick is not replacing all "(" with "[", only the ones that occur immediately after exp and the corresponding pair.

like image 726
lenzinho Avatar asked Jan 06 '23 20:01

lenzinho


1 Answers

You can do that with a vim macro.

Let's clear the a register by pressing qaq. ( In case if any previous operations are recorded, we can clear them)

Start a macro recording by pressing qa. Search for exp( by typing/exp(/e. this will put the cursor at (. Press % to move to its closing bracket. Press r] to replace it with ]. Now, press N to move to exp(. Press r[ to replace it with [. Press @a to recursively replace all such instances. Press q to stop recording.

Now, you can press@a to play the macro and it will replace everywhere.

like image 136
SibiCoder Avatar answered Jan 17 '23 08:01

SibiCoder