Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

gawk - awk not rounding with OFMT and $0

I'm printing an array with 100 columns and I would like all columns to have 2 decimals. I would like to use print $0 and not have to individually specify the format for all columns.

OFMT does seen to work with $0:

echo '0.77767686 0.76555555 0.6667667 0.77878878' |awk '{CONVFMT="%.2g";OFMT="%.2g";print ($0+0);print ($0+0)"";print $0}' 

Results:

0.78
0.78
0.77767686 0.76555555 0.6667667 0.77878878
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note that all input is treated as strings until implicitly converted by how it is used.

OFMT is used when strings are converted to numbers numbers are printed, e.g.:

<<< 0.77767686 awk '{ print 0+$0 }' OFMT='%.2g'

CONVFMT is used when numbers are explicitly converted to strings, e.g.:

<<< 0.77767686 awk '{ print "" 0+$0 }' CONVFMT='%.2g'

Output in both cases:

0.78

The latter converts $0 into a number and then concatenates it with the empty string.

To achieve this for every column I would suggest using a sensible setting of the input and output record separators:

<<< '0.77767686 0.76555555 0.6667667 0.77878878' 
awk '{ print 0+$0 RT }' CONVFMT='%.2g' RS='[ 
]+' ORS=''

Note the two conversions, first to a number with 0+$0 then back to a string by concatenating it with RT. RT will be set to the matched record separator. Note that this is GNU awk specific, for a more portable solution, use a loop, e.g.:

<<< '0.77767686 0.76555555 0.6667667 0.77878878' 
awk '{ for (i=1; i<=NF; i++) $i+=0 } 1' CONVFMT='%.2g'

Output in both cases:

0.78 0.77 0.67 0.78

Edit - Responding to @BeeOnRope

@BeeOnRope is correct, OFMT is used as the format specifier when the print-function calls sprintf(), while CONVFMT is used in other conversions. Here is an example that illustrates the difference:

<<< 0.77767686 awk '{ n=0+$1; s=""n; print n, s }' OFMT='%.2g' CONVFMT='%.3g'

Output:

0.78 0.778

Two relevant sections from the GNU awk manual:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...