2

I have the following output from Mathematica to C code:

$ cat file.txt
Complex(1.3, 2.7)*Power(kappa, 2.0) + Complex(0.3, 2.0)*Power(kappa,5.0)*log(alpha)

The file is extremely long (many tens of thousands of lines). I would like to replace every Complex(a, b) with (a + i*b) and every Power(a, b) to a^b. So the above sample would look like:

$ cat desired_file.txt
(1.3 + i*2.7)*kappa^2.0 + (0.3 + i*2.0)*kappa^5.0*log(alpha)

How can I use sed to achieve this result? It is not straight forward at all by reading regular expressions and examples out there.

How can I do this using sed?

  • Would the easiest solution not just be to create your own Complex and Power functions in Matlab? – Graeme Jun 28 '14 at 12:05
3

This should do it:

sed 's/Complex(\([^,]*\), *\([^)]*\))/(\1 + i*\2)/g; 
     s/Power(\([^,]*\), *\([^)]*\))/\1^\2/g' file

This will not work for nested statements like Power(Power(a, b), c).

Explanation

  • To susbstitute patterns in sed, you use the substitution operator (s/pattern/replacement/). The g at the end means global, it causes the substitution to be applied to all matches.

  • Patterns can be captured and reused later by placing them inside escaped parentheses: \( and \). The first such pattern is \1, the second \2 etc.

  • To replace Complex(a, b), I use Complex(\([^,]*\), *\([^)]*\)). This means match Complex(, then the longest string of consecutive non-, characters ([^,]*) is captured as \1, then a single comma and zero or more spaces, then the longest string of non-) characters until the closing parenthesis is found. The whole thing is replaced with (\1 + i*\2).

  • The regular expression that matches the Power() is essentially the same.

0

You can use sed's string replace function:

sed -i 's/"complex(a, b)"/(a + i*b)/g'

The same for the other pattern, just replace complex(a,b) with the expression you want to replace and (a + i*b) with the string you want instead of that expression.

  • 1
    I think the OP is asking for the expression to replace. – terdon Jun 28 '14 at 13:02
  • @terdon sorry, I misunderstood something. – psimon Jun 28 '14 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.