sodiumnitrate
sodiumnitrate

Reputation: 3133

Awk formatted output how to include sign for floats

I want to reformat a file by adjusting the spacing between fields. I have the managed to get the content into this form:

  130GLU    HB2  383   0.058   5.178   2.925
  130GLU     CG  384   -0.108   5.065   2.887
  130GLU    HG1  385   -0.079   5.007   2.963

What I can't get right is the floats with minus signs. The above formatting is produced by awk '{printf " %6s%7s%5s %5.3f %5.3f %5.3f\n",$1,$2,$3,$4,$5,$6}' file. However, I want to get the following:

  130GLU    HB2  383   0.058   5.178   2.925
  130GLU     CG  384  -0.108   5.065   2.887
  130GLU    HG1  385  -0.079   5.007   2.963

In other words, account for the sign in counting the characters of the number, in this case the 5 part of %5.3f. How can I do this?

Upvotes: 0

Views: 97

Answers (1)

zedfoxus
zedfoxus

Reputation: 37099

Just a simple change - see if it works:

awk '{printf "  %6s%7s%5s   % 5.3f   % 5.3f   % 5.3f\n",$1,$2,$3,$4,$5,$6}' file
Result:
  130GLU    HB2  383    0.058    5.178    2.925
  130GLU     CG  384   -0.108    5.065    2.887
  130GLU    HG1  385   -0.079    5.007    2.963

or

awk '{printf "  %6s%7s%5s   %+5.3f   %+5.3f   %+5.3f\n",$1,$2,$3,$4,$5,$6}'
Result:
  130GLU    HB2  383   +0.058   5.178   2.925
  130GLU     CG  384   -0.108   5.065   2.887
  130GLU    HG1  385   -0.079   5.007   2.963

Edit:

awk '{printf "  %6s%7s%5s  % 5.3f  % 5.3f  % 5.3f\n",$1,$2,$3,$4,$5,$6}' file
Result:
  130GLU    HB2  383   0.058   5.178   2.925
  130GLU     CG  384  -0.108   5.065   2.887
  130GLU    HG1  385  -0.079   5.007   2.963

Upvotes: 2

Related Questions