awk reduce decimals for a single multiple input values

牧云@^-^@ 提交于 2020-01-15 18:50:56

问题


I want to transform the following

82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31

into

82.8, 69.3, 44.0, 33.4, 26.8, ...

I think awk seems to be the easy way to do this. The following does work for a single input value

echo 123.45567 | awk '{printf("%.1f\n", $1)}'

How can I do this for the above multiple input values with the space delimiter with awk or is there any better way to do this? Yesterday I was trying with java script which didn't work.


回答1:


Just loop over each field:

$ awk  -F', ' '{for(i=1;i<=NF;i++)printf "%.1f%s",$i,(i==NF?RS:FS)}'

By setting the field separator to be , (a comma followed by a space) the input format is preserved in the output. The condition (i==NF?RS:FS) checks if we have reached the last field in the record and separates the output accordingly.




回答2:


Using awk, you can loop trough all fields.

awk '{for (i=1;i<=NF;i++) printf("%.1f, ",$i);print ""}' file
82.8, 69.3, 43.8, 33.4, 26.9, 26.8, 24.9, 24.9, 24.7, 23.1, 19.3, 17.5,



回答3:


Use it like this:

s='82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31, 17.51.'
awk '{printf("%.1f\n", $1)}' RS=, <<< "$s"
82.8
69.3
43.8
33.4
26.9
26.8
24.9
24.9
24.7
23.1
19.3
17.5



回答4:


Q: how can I do this for the above multiple input values with the space delimiter with awk

A: Try setting the RS record separator to a space:

echo '82.77 69.30 43.75 33.44 26.88 26.83 24.89 24.88 24.74 23.07 19.31 17.51' \ 
| awk 'BEGIN{RS=" "} {printf("%.1f\n", $1)}' 
82.8
69.3
43.8
33.4
26.9
26.8
24.9
24.9
24.7
23.1
19.3
17.5


来源:https://stackoverflow.com/questions/20371150/awk-reduce-decimals-for-a-single-multiple-input-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!