awk in complex number data

Hi,

I'm trying to transform my data from the following format:

eps:, 0.248281687841641, -2.83539034165844e-7, 2.78042576353472+6.3505226053266e-6i

to this:

eps:, 0.248281687841641, -2.83539034165844e-7, 2.78042576353472, +6.3505226053266e-6

so I can plot it with GnuPlot.

how do I change " a+bi " to " a, b " using awk?

Any help is appreciated. :slight_smile:

---------- Post updated at 06:22 PM ---------- Previous update was at 05:42 PM ----------

I could solve it myself using these two sed commands:
sed "s/+/, &/;s/i/ /" eps.out > eps2.out

What if the imaginary part is negative as in the cube root of -1?

1 Like

In that case I wait for your response... :frowning:
For my first file I didn't have negative imaginary part.

Try

sed -r 's/([^ e])([+-])/\1, \2/g; s/i//g' file
eps:, 0.248281687841641, -2.83539034165844e-7, 2.78042576353472, +6.3505226053266e-6
eps:, 0.248281687841641, -2.83539034165844e-7, 2.78042576353472, -6.3505226053266e-6
1 Like

I'm sorry, but waiting for us to tell you what the format is for your input data seems extremely backwards. You should be able to either show us the format that is used to print the last field in your input file, show us the output for a data sample with a negative imaginary part, or explicitly state that there will NEVER be any negative imaginary parts.

In addition to what RudiC suggested and assuming that if there are any negative imaginary parts in your complex numbers, they use a - instead of a + to separate the real and imaginary parts; you could modify your sed command to cover both cases (assuming you are using a standards conforming sed with an extension that allows multiple substitute commands to be separated on one line by a semicolon [as was used in your code]):

sed 's/\([0-9]\)\([-+][0-9]\)/\1, \2/; s/i//' eps.out > eps2.out

or, if there could be more than one complex number on a line:

sed 's/\([0-9]\)\([-+][0-9]\)/\1, \2/g; s/i//g' eps.out > eps2.out

If you're using a GNU sed which does not always adhere to the standards, you might need to use:

sed --posix 's/\([0-9]\)\([-+][0-9]\)/\1, \2/g; s/i//g' eps.out > eps2.out

to make it work. If you would tell us what operating system and shell you're using when you submit questions like this, those of us trying to help you would be able to determine which code suggestion might work for you without making assumptions about what OS you might be using.

1 Like