Search code examples
unixscientific-notation

Floating Point to Scientific Format in UNIX


I have some data in this form:

0.123456 11.234567 -22.345678
-3.456789 4.567891 -5.678912 etc

I would like to convert them in a matrix with 8columns in a scientific format with +- sign, one number before and 6 numbers after the decimal point, such as:

+0.123456E+00 +1.123456E+01  -2.234567E+01 etc

I've tried something like this but it doesn't work:

sed -n '31,46p' $filename1|xargs -n8|printf "%13.6e" >>file2.txt

Any ideas?


Solution

  • I would use this:

    xargs -n 8 < file | awk '{for (i=1;i<NF;i++) printf ("%13.6e%s", $i, FS); printf ("%13.6e\n", $NF)}'
    
    • xargs -n X < file comes from your previous question: How to format the data of a file in Unix?
    • awk '{for (i=1;i<NF;i++) printf ("%13.6e%s", $i, FS); printf ("%13.6e\n", $NF)}' loops through the items in a line and prints them with the specific format %13.6e, together with a space. Then, it prints the last field and a new line.

    See a test

    $ cat a
    0.123456 11.234567 -22.345678
    -3.456789 4.567891 -5.678912
    2.342 23.111 123.23 22
    $ xargs -n 8 < a | awk '{for (i=1;i<NF;i++) printf ("%13.6e%s", $i, FS); printf ("%13.6e\n", $NF)}'
    1.234560e-01  1.123457e+01 -2.234568e+01 -3.456789e+00  4.567891e+00 -5.678912e+00  2.342000e+00  2.311100e+01
    1.232300e+02  2.200000e+01