LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk on number columns and format problem (http://www.linuxquestions.org/questions/programming-9/awk-on-number-columns-and-format-problem-899600/)

cristalp 08-26-2011 09:13 AM

awk on number columns and format problem
 
I am editing a file with 8 columns inside.

The file looks like:
Code:

0, 1, 7, 1.371E+02, 5.925E-01,-7.976E+00, 1.185E+00,0,
0, 1, 8, 3.689E+01, 1.742E-01, 1.156E+00, 3.485E-01,0,
0, 1, 9, 1.619E+02, 7.475E-01,-7.284E+00, 1.495E+00,0,

I want to just take the square for the number of the 6th column and keep the other columns unchanged. And, I really want to keep the format of the input and edited files are exactly same, which means the spaces between columns and the commas and the format of everything all the same after editing.

My awk code is:

Code:

awk 'BEGIN {OFMT="%.3E";FS=OFS=","}{$6=$6*$6;print}' FILENAME
The output is:
Code:

0, 1, 7, 1.371E+02, 5.925E-01,63.6166, 1.185E+00,0,
0, 1, 8, 3.689E+01, 1.742E-01,1.33634, 3.485E-01,0,
0, 1, 9, 1.619E+02, 7.475E-01,53.0567, 1.495E+00,0,

Which means that the OFMT="%.3E" action does not work. You can see the 6th column are not in *.***+E** format.

However if I delete the part FS=OFS="," in action:
Code:

awk 'BEGIN {OFMT="%.3E"}{$6=$6*$6;print}' FILENAME
The output gives right format 1.111E+00 for the 6th columns. But then, the spaces between everything just mess up.

I don't understand why. It seems my code is well fit the standard. Could anybody explain a bit? What I should do to improve and achieve what I want?

Many Thanks!

colucix 08-26-2011 09:24 AM

First, if you omit the FS specification, the sixth fields in the first and second line are 1.185E+00 and 1.495E+00 respectively, because the sixth value is negative and there is no space between the comma and the minus sign. Said that, I think the problem is in the OFMT specification: according to the GAWK manual:
Quote:

According to the POSIX standard, awk's behavior is undefined if OFMT contains anything but a floating-point conversion specification.
You can override the problem using sprintf to convert $6 in the format you want:
Code:

$ cat file
0, 1, 7, 1.371E+02, 5.925E-01,-7.976E+00, 1.185E+00,0,
0, 1, 8, 3.689E+01, 1.742E-01, 1.156E+00, 3.485E-01,0,
0, 1, 9, 1.619E+02, 7.475E-01,-7.284E+00, 1.495E+00,0,
$ awk -F, 'BEGIN{FS=OFS=","}{$6=$6*$6; $6=sprintf(" %.3E",$6); print}' file
0, 1, 7, 1.371E+02, 5.925E-01, 6.362E+01, 1.185E+00,0,
0, 1, 8, 3.689E+01, 1.742E-01, 1.336E+00, 3.485E-01,0,
0, 1, 9, 1.619E+02, 7.475E-01, 5.306E+01, 1.495E+00,0,


grail 08-26-2011 09:49 AM

colucix's solution is correct and can also be written as:
Code:

awk 'BEGIN{FS=OFS=","}$6 = sprintf("%.3E",$6^2)' file

cristalp 08-30-2011 07:14 AM

Thanks guys!! I think by now I can say this question has been solved.

Thanks for all your kind help!!!;)


All times are GMT -5. The time now is 10:18 PM.