yihang hwang
yihang hwang

Reputation: 419

How to format decimal space using awk in linux

original file :

a|||a 2 0.111111
a|||book 1 0.0555556
a|||is 2 0.111111

now i need to control third columns with 6 decimal space

after i tried awk {'print $1,$2; printf "%.6f\t",$3'} but the output is not what I want

result :

a|||a 2
0.111111        a|||book 1
0.055556        a|||is 2

that's weird , how can I do that will just modify third columns

Upvotes: 0

Views: 275

Answers (2)

123
123

Reputation: 11246

Print adds a newline on the end of printed strings, whereas printf by default doesn't. This means a newline is added after every second field and none is added after the third.

You can use printf for the whole string and manually add a newline.

Also I'm not sure why you are adding a tab to the end of the lines, so i removed that

awk '{printf "%s %d %.6f\n",$1,$2,$3}' file

a|||a 2 0.111111
a|||book 1 0.055556
a|||is 2 0.111111

Upvotes: 1

Birei
Birei

Reputation: 36282

Your print() is adding a newline character. Include your third field inside it, but formatted. Try with sprintf() function, like:

awk '{print $1,$2, sprintf("%.6f", $3)}' infile

That yields:

a|||a 2 0.111111
a|||book 1 0.055556
a|||is 2 0.111111

Upvotes: 1

Related Questions