AWK – Modify One Column but Print All

awk

I would like to modify $2 with the following code:

cat file | awk '{printf "%.15f\n", $2 = 1-$2}' > new_file

The code does its job, it prints 15 decimals and calculates 1-n. However, it does not print the other columns. If I try to do that with the following code it does print it, but to a different line:

cat file | awk '{printf "%.15f\n", $2 = 1-$2; print $0}' > new_file

My original file:

752566 0.883928571428571 1 rs3094315 0
752721 0.765873015873016 1 rs3131972 0
752894 0.883928571428571 1 rs3131971 0
753541 0.268849206349206 1 rs2073813 0

Output:

752566 0.116071 1 rs3094315 0
0.116071428571429

Desired output (the order of the columns does not matter):

752566 1 rs3094315 0 0.116071428571429

Best Answer

You can use sprintf to print the new value to a formatted string, and assign that as the new value of $2:

$2 = sprintf("%.15f",1-$2)

Then it's just a matter of printing the whole (modified) record:

$ awk '{$2 = sprintf("%.15f",1-$2); print}' file
752566 0.116071428571429 1 rs3094315 0
752721 0.234126984126984 1 rs3131972 0
752894 0.116071428571429 1 rs3131971 0
753541 0.731150793650794 1 rs2073813 0
Related Question