32

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 output file

1 2
1 5
2 3
2 0

Thanks for your help.

Tony
  • 2,889
  • 8
  • 41
  • 45

6 Answers6

50

try the int() function

awk '{$2=int($2)}1' file
kurumi
  • 25,121
  • 5
  • 44
  • 52
  • 1
    Note, this does the same as %d in a printf and rounds things down, 3.9763333 will be printed as 3 – vickirk Feb 21 '11 at 17:38
6
awk '{printf("%d %d\n"), $1, $2;}' inputFileName
qbert220
  • 11,220
  • 4
  • 31
  • 31
3

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

awk '{printf "%s %d\n", $1, $2}'
Will
  • 24,082
  • 14
  • 97
  • 108
0

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
nisetama
  • 7,764
  • 1
  • 34
  • 21
0

The following should do this

{ printf "%s %.0f\n", $1, $2}
vickirk
  • 3,979
  • 2
  • 22
  • 37
0

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

awk '{split($2,a,"."); print $1" "a[1]}'
  • how about : `awk -F"[ \t.]" '{print $1, $2}' file`. no need to create extra array. :) – kurumi Feb 17 '11 at 10:41
  • @kurumi: Looks good, but what if there's point in the first number? But we can use `$(NF-1)` –  Feb 17 '11 at 11:51