Rounding floating number using AWK

本小妞迷上赌 提交于 2020-11-29 05:01:27

问题


I have a file b.xyz as,

-19.794325 -23.350704 -9.552335
-20.313872 -23.948248 -8.924463
-18.810708 -23.571757 -9.494047
-20.048543 -23.660052 -10.478968

I want to limit each of the entries to three decimal digits.

I tried this one

awk '{ $1=sprintf("%.3f",$1)} {$2=sprintf("%.3f",$2)} {$3=sprintf("%.3f",$3)} {print $1, $2, $3}' b.xyz

it works for three columns, but how to expand it to apply for n/all columns?


回答1:


If you will always have three fields, then you can use:

$ awk '{printf "%.3f %.3f %.3f\n", $1, $2, $3}' file
-19.794 -23.351 -9.552
-20.314 -23.948 -8.924
-18.811 -23.572 -9.494
-20.049 -23.660 -10.479

For an undefined number of lines, you can do:

$ awk '{for (i=1; i<=NF; i++) printf "%.3f%s", $i, (i==NF?"\n":" ")}' file
-19.794 -23.351 -9.552
-20.314 -23.948 -8.924
-18.811 -23.572 -9.494
-20.049 -23.660 -10.479

It will loop through all the fields and print them. (i==NF?"\n":" ") prints a new line when the last item is reached.

Or even (thanks Jotne!):

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

Example

$ cat a
-19.794325 -23.350704 -9.552335 2.13423 23 23223.23 23.23442
-20.313872 -23.948248 -8.924463
-18.810708 -23.571757 -9.494047
-20.048543 -23.660052 -10.478968

$ awk '{for (i=1; i<=NF; i++) printf "%.3f %s", $i, (i==NF?"\n":" ")}' a
-19.794 -23.351 -9.552  2.134  23.000  23223.230  23.234 
-20.314 -23.948 -8.924 
-18.811 -23.572 -9.494 
-20.049 -23.660 -10.479 

$ awk '{for (i=1; i<=NF; i++) printf "%.3f %s", $i, (i==NF?RS:FS)}' a
-19.794  -23.351  -9.552  2.134  23.000  23223.230  23.234 
-20.314  -23.948  -8.924 
-18.811  -23.572  -9.494 
-20.049  -23.660  -10.479


来源:https://stackoverflow.com/questions/22306770/rounding-floating-number-using-awk

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