AWK不OFMT和$ 0个圆 [英] awk not rounding with OFMT and $0
问题描述
我打印100列的一个阵列,我想所有列有2位小数。我想用打印$ 0,不必单独指定格式的所有列。
OFMT没有见过$ 0到工作:
回声'0.77767686 0.76555555 0.6667667 0.77878878'| awk的'{CONVFMT =%2克。OFMT =%2克打印($ 0 + 0);打印($ 0 + 0);打印$ 0}
结果:
0.78
0.78
0.77767686 0.76555555 0.6667667 0.77878878
请注意,所有的输入视为字符串,直到隐含如何使用它进行转换。
OFMT
时,将字符串转换成数字被使用,例如:
<<< 0.77767686的awk'{0打印+ $ 0}'OFMT ='%。2g'上
CONVFMT
时数转换成字符串使用的,例如:
<<< 0.77767686的awk'{打印,0 + $ 0}'CONVFMT ='%。2g'上
在这两种情况下输出:
0.78
后者转换 $ 1,0
成一个号码,然后用空字符串并置了。
要实现这一点,每列我建议使用的输入和输出记录分隔符的一个合理的设置:
<<< 0.77767686 0.76555555 0.6667667 0.77878878'\\
AWK'{0打印+ $ 0 RT}'CONVFMT ='%。2g'上RS ='[\\ t \\ n] +'ORS =''
请注意这两个转换,先用 0 + $ 0
然后回用 RT串联成为一个字符串$ C $一个数字C>。
RT
将被设置为匹配的记录分隔符。
输出:
0.78 0.77 0.67 0.78
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
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, e.g.:
<<< 0.77767686 awk '{ print 0+$0 }' OFMT='%.2g'
CONVFMT
is used when numbers are converted into 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='[ \t\n]+' 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.
Output:
0.78 0.77 0.67 0.78
这篇关于AWK不OFMT和$ 0个圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!