简体   繁体   中英

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'} 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM