使用awk格式转换器保持真实值

时间:2013-09-30 10:45:52

标签: awk integer format

我最近问过following question使用awk的格式转换,Ed Morton回答了这个问题。但是,我需要协助在此awk代码中进行调整。 创建文件时,awk脚本似乎向下舍入到最接近的整数,而不是保留实际的整数值(包含小数)。有没有办法修改此脚本以保持数据集中的实际值。

例如:

church place 3.43
church institution 6.92
man place 86.39
man food 63.39
woman book 37.04

变为

@relation 'filename'
@attribute "place" string
@attribute "institution" string
@attribute "food" string
@attribute "book" string


@data
3,6,0,0,church
86,0,63,0,man
0,0,0,37,woman

而不是

@relation 'filename'
@attribute "place" string
@attribute "institution" string
@attribute "food" string
@attribute "book" string


@data
3.43,6.92,0,0,church
86.39,0,63.39,0,man
0,0,0,37.04,woman

有没有办法可以改变来自this response的awk以包含实际值而不是仅舍入到最接近的整数?

1 个答案:

答案 0 :(得分:1)

打印数值时使用%g或%s而不是%d,例如:

printf "%g,", score[row,attr]

printf "%s,", score[row,attr]+0

请注意,在使用%s时需要添加零,以便将空字符串转换为数字零。