With awk
:
awk '{ printf("%.3g %.3g\n", $1, $2) }' file
With the given data, this produces
0.993 0.00704
0.646 0.354
0.993 0.00704
0.993 0.00704
0.993 0.00704
0.993 0.00704
0.993 0.00704
0.993 0.00704
0.5 0.5
Note that 0.00704 has five decimals, but three significant digits.
If you want exactly three decimals, use %.3f
instead of %.3g
and get
0.993 0.007
0.646 0.354
0.993 0.007
0.993 0.007
0.993 0.007
0.993 0.007
0.993 0.007
0.993 0.007
0.500 0.500
The two variation above may be generalised for a variable number of columns, using GNU awk
:
awk -v CONVFMT='%.3g' '{ for (i=1; i<=NF; ++i) $i+=0; print }' file
The loop with $i+=0
forces awk
to re-format the value of every field as a floating point number, which it will do while taking CONVFMT
into account (it will more or less do the equivalent of $i=sprintf(CONVFMT, $i)
).
If you want to cut the numbers:
awk '{ for (i=1; i<=NF; ++i) $i=sprintf("%.5s", $i); print }' file
This treats the numbers as strings and cuts them off after five characters (which assumes that all numbers are less than 10 and greater than zero) generating
0.992 0.007
0.646 0.353
0.992 0.007
0.992 0.007
0.992 0.007
0.992 0.007
0.992 0.007
0.992 0.007
0.5 0.5
For a slightly more general cutting of the numbers:
awk '{ for (i=1; i<=NF; ++i) if (match($i,".*\\.[0-9]?[0-9]?[0-9]?")) $i=substr($i,RSTART,RLENGTH); print }' file
The operation in the loop cuts the numbers at the point at which the given regular expression match ends (if it matches).