I have a csv file that contain 3 fields of data. I need to reformat it so that the output, particularly in the 3rd field is right justified.
Input
-159.4031,22.2341,96.52
-159.4009,22.2341,95.85
-159.4774,22.2319,114.09
-159.4054,22.2319,97.65
This is the awk command that I am working with but 3rd field is left justified.
awk '{ printf " %.4f %.4f %.2f\n", $1, $2, $3 }'
-159.4031 22.2341 96.52
-159.4009 22.2341 95.85
-159.4774 22.2319 114.09
-159.4054 22.2319 97.65
My desired output is:
-159.4031 22.2341 96.52
-159.4009 22.2341 95.85
-159.4774 22.2319 114.09
-159.4054 22.2319 97.65
What am I doing wrong?
@ncwxpanther , welcome
something along ...
awk -F, '{ printf " %.4f %.4f %6.2f\n", $1, $2, $3 }' /tmp/input
-159.4031 22.2341 96.52
-159.4009 22.2341 95.85
-159.4774 22.2319 114.09
-159.4054 22.2319 97.65
I edited mine ...
1 Like
I have edited my desired output.
After the dot there is the number of digits after the decimal point.
Before the dot there is the total field width, right justified and space-padded. A -
before that number means left justified.
It seems possible that the first two fields might also vary in length at some time, so it might be wise to apply the (maximum possible ) total width to all columns.
Note that awk (or any printf in C or Bash, for example) will never truncate a field to the total field width. It will always show all the data, in preference to retaining the formatting.
The part after the decimal point is treated differently: that part of the value is rounded to fit in the specified length given after the dot.
%.4f
is %0.4f
, the field width is zero, all values exceed the field width, so no adjustment within the field is possible.
You might want
printf "%10.4f %9.4f %7.2f\n", $1, $2, $3
so the given values fit in the fields and are adjusted.
Assume the longest possible numbers (values) for each column, and make a test with them!
1 Like