printf - awk rounding floating number -
i have 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 limit each of entries 3 decimal digits.
i tried one
awk '{ $1=sprintf("%.3f",$1)} {$2=sprintf("%.3f",$2)} {$3=sprintf("%.3f",$3)} {print $1, $2, $3}' b.xyz
it works 3 columns, how expand apply n/all columns?
if have 3 fields, 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 undefined number of lines, 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 loop through fields , print them. (i==nf?"\n":" ")
prints new line when last item reached.
or (thanks jotne!):
awk '{for (i=1; i<=nf; i++) printf "%.3f %s", $i, (i==nf?rs:fs)}' file
example
$ cat -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":" ")}' -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)}' -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
Comments
Post a Comment