Print multiple columns in scientific notation

Hi everybody,

I have file 1 with 15 columns, I want to change the formatting of the numbers of columns 10,11 and 12 in the scientific notation.
I used the Following script:

awk '{print $10}' file1.dat | awk '{printf "%.2e\n", $1}' > file2.dat
awk '{print $11}' file1.dat | awk '{printf "%.2e\n", $1}' > file3.dat
awk '{print $12}' file1.dat | awk '{printf "%.2e\n", $1}' > file4.dat

I have two questions:

a)How to make changes simultaneously and get these three columns printed in one file? I tried this, but only the column 10 was printed:

awk '{print $10, $11, $12 }' file1.dat | awk '{printf "%.2e\n", $1, $2, $3 }' > file5.dat

b) Is it possible to get the formatting conversion of columns 10,11,12 directly in file1.dat , without having to generate extra files?

Thank you!

Welcome to the forum.

I'm pretty sure that what you want can be done, but I don't really understand what you want. Do want to keep the 15 fields, but change fileds' 10, 11, and 12 formatting? And, reflect that back into the original file?
A representative sample would help people in here help you...

BTW, the problem in your second code sample is that you supply only one single format string for three values - supply three!

Thank you!

Yes, exactly, I want to keep the 15 fields, but change the formatting of the fields 10, 11, and 12 in the original file. The input is:

304 1 2 3 0.079 7 0.666 0.0 0.88 0.000201 0.000201 0.001810 39 10 179
307 4 5 6 0.079 8 0.666 0.0 1.55 0.000319 0.000319 0.000654 35 10 175

and the output should be:

304 1 2 3 0.079 7 0.666 0.0 0.88 2.01E-04 2.01E-04 1.81E-03 39 10 179
 307 4 5 6 0.079 8 0.666 0.0 1.55 3.19E-04 3.19E-04 6.54E-04 35 10 175
awk -v f='10 11 12' 'BEGIN{split(f,a)} {for(i=1; i in a;i++) $a=sprintf("%.2e", $a)}1' myFile
1 Like

Try also

awk '{$10+=0; $11+=0; $12+=0}1' CONVFMT="%.2e" file

And, you can't modify the file in place (even the editors that claim doing so work on temporary file overwriting the original with the result). You have to redirect the result to another file, and then mv / cp it back to file1 .

2 Likes

Thanks vgersh99, your code works perfectly.

Thanks also to RudiC, but there is a problem. Indeed, not all numbers get their formatting changed to the scientific notation, especially in the column 12. With your code the input is:

383 3 4 5 0.07 1 0.66 1.7 0.66 0.000351 0.000351 195.0 35 7 97
395 6 8 9 0.07 2 0.66 2.0 1.11 0.000379 0.000379 515.0 32 8 89

and the output:

383 3 4 5 0.07 1 0.66 1.7 0.66 3.51e-04 3.51e-04 195 35 7 97
395 6 8 9 0.07 2 0.66 2.0 1.11 3.79e-04 3.79e-04 515 32 8 89

Yes, this is a feature of awk : if the variable has an integer value, it uses %d , not the defined default format... Try

awk '{$10+=1e-9; $11+=1e-9; $12+=1e-9}1' CONVFMT="%.2e" file
1 Like

Now it works perfectly, many thanks!