开发者

How to truncate of a real value and discard its non-integer part in awk?

I have the following dataset (all positive values)

Input file

1 2.3456
1 5.02
2 3.9763333
2 0.123

I would like to truncate the numbers in the second column and discard its non-integer part.

How would one do it in awk?

Desired开发者_如何学JAVA output file

1 2
1 5
2 3
2 0

Thanks for your help.


try the int() function

awk '{$2=int($2)}1' file


awk '{printf("%d %d\n"), $1, $2;}' inputFileName


Since you want to truncate rather than round, use %d instead of %0.f:

awk '{printf "%s %d\n", $1, $2}'


The following should do this

{ printf "%s %.0f\n", $1, $2}


I've upvoted everyone but for the fun of it here's another one:)

awk '{split($2,a,"."); print $1" "a[1]}'


If others search for how to floor numbers so that for example -0.1 is converted to -1, you can do something like this:

$ printf %s\\n -1 -.9 -.1 0 .1 .9 1|awk '{x=int($0);print(x==$0||$0>0)?x:x-1}'
-1
-1
-1
0
0
0
1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜