0

I have a csv file with number representations of complex numbers.

-0.0272780+88932190i
0.2833029-10293882i
0.1990238+22901020i
0.3009823-22389991i

This is a HUGE file and I would like to translate that into a complex number representation in a C header file.

const Ipp32fc complexes[] = {
    {-0.0272780,88932190 },
    { 0.2833029,10293882 },
    { 0.1990238,22901020 }
    { 0.3009823,22389991 },
     ... // you get the idea

In Find/Replace I have tried

[\+-]$

or

[\+-](+)$

to replace the inner signs with comma then I was going to perform a simple Find/Replace on i and strip that out.

Can't seem to get the right regex.

4
  • 1
    Why are you deleting the sign off of the imaginary parts?
    – Kusalananda
    Jan 28, 2020 at 13:02
  • You write it is a CSV file. Is this only one column of many, or does the file only contain that one column?
    – AdminBee
    Jan 28, 2020 at 13:03
  • It is just one number each in it's own column. That's all. Only one column in the file. In answer to the other question...I'm not sure that is accepted. School me if I'm wrong. Jan 28, 2020 at 13:13
  • That's correct. We may have a misunderstanding Jan 28, 2020 at 13:17

1 Answer 1

2

Using awk on the command line:

$ awk 'BEGIN { print "const Ipp32fc complexes[] = {" } END { print "};" } { re=im=$0; sub("[+-][0-9.]*i$", "", re); sub("^-?[0-9.]*", "", im); sub("i$", "", im); printf "\t{ %s, %s },\n", re, im }' file
const Ipp32fc complexes[] = {
        { -0.0272780, +88932190 },
        { 0.2833029, -10293882 },
        { 0.1990238, +22901020 },
        { 0.3009823, -22389991 },
};

The awk command with a bit of whitespace added:

awk '
    BEGIN { print "const Ipp32fc complexes[] = {" }
    END   { print "};" }
    {
        re = im = $0
        sub("[+-][0-9.]*i$", "", re)
        sub("^-?[0-9.]*", "", im)
        sub("i$", "", im)
        printf "\t{ %s, %s },\n", re, im
    }' file

This prints out the needed C language header and footer text in the BEGIN and END blocks, while the input is parsed in the longer block.

The input from each line is assigned to both the re and im variables. The re variable gets everything after the imaginary part chopped off, while the im variable gots the real part and the i removed.

Numbers are assumed to contain only digits and dots.

The data is then printed.

5
  • I'll give it a go. Unfortunately I am on a Windows box. Jan 28, 2020 at 13:14
  • @jiveturkey This is a "Unix & Linux" site.
    – Kusalananda
    Jan 28, 2020 at 13:15
  • I understand, I was going to utilize Ubuntu on Windows 10 Jan 28, 2020 at 13:16
  • @jiveturkey That should be ok. The only issue is if your input file is a DOS text file. In that case, run dos2unix on the file first.
    – Kusalananda
    Jan 28, 2020 at 13:17
  • Thanks. Still working it. Problem is on a different computer so writing :) Jan 28, 2020 at 13:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .