lenzinho
lenzinho

Reputation: 401

replacing brackets

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.

Upvotes: 4

Views: 240

Answers (3)

Totorow
Totorow

Reputation: 1

Just like Sibi's answer, but just a subtle change, you should use `` to jump back to the matching brace instead of N. otherwise it doesn't work with this pattern: exp(...exp(...))

Upvotes: 0

JJoao
JJoao

Reputation: 5347

In the following sed script (brackreplace) we are:

  • exp(Exp§
  • hide balanced (...)«...» (if they have no "()§" inside)
  • Exp§...)Exp[...]
  • restoring hidden parentesis
#!/bin/sed -zf 

s/exp(/Exp§/g                    # (1) protect        exp( →  Exp§
s/(\([^()§]*\))/«\1»/g           # (2) hide balanced  (...) → «...» 

s/Exp§\([^()§]*\))/Exp[\1]/g     # (3) Exp§...) → Exp[...]
s/«/(/g                          # restore protected parentesis
s/»/)/g 

This cover your example; repeat line (2) if you expect deeper () inside exp(...).

After chmod, this command may be used in command line or inside the editor. Example with vim:

:%!bracketreplace

Upvotes: 0

SibiCoder
SibiCoder

Reputation: 1496

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.

Upvotes: 9

Related Questions