Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how make float to integer in awk

Tags:

I have a variable in my awk code . after some arithmatic operation on this variable and printing (print $1,$2,variable) the result is made like below:

my result

Bama     2   5     Bama     2   5.001 Bama     2   5.002 Bama     2   5.003 Bama     2   5.004 Bama     2   6   Bama     2   6.003 Bama     2   6.004 Bama     2   4.005   

But i want only integer section of my variable print

desired result

Bama     2   5     Bama     2   5 Bama     2   5 Bama     2   5 Bama     2   5 Bama     2   6   Bama     2   6 Bama     2   6 Bama     2   4 

How can I do this?

like image 950
mohammad Avatar asked Oct 17 '12 08:10

mohammad


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

How do you round off in awk?

According to the GNU awk manual, The way printf and sprintf() (see Printf) perform rounding often depends upon the system's C sprintf() subroutine. On many machines, sprintf() rounding is “unbiased,” which means it doesn't always round a trailing '.

What does awk NF do?

The “NF” AWK variable is used to print the number of fields in all the lines of any provided file. This built-in variable iterates through all the lines of the file one by one and prints the number of fields separately for each line.

What does $1 $2 indicate in awk file?

The variable $1 represents the contents of field 1 which in Figure 2 would be "-rwxr-xr-x." $2 represents field 2 which is "1" in Figure 2 and so on. The awk variables $1 or $2 through $nn represent the fields of each record and should not be confused with shell variables that use the same style of names.


2 Answers

Truncate it using the int function:

print $1, $2, int( variable ); 
like image 139
Birei Avatar answered Oct 21 '22 13:10

Birei


To keep exactly same spacing and everything:

awk -F ' ' '{print $1"     "$2"   "int($3)}' data.lst 

this trims, does not round, so 4.9 will become 4.

A dirty way is to use the point as field separator:

awk -F '.' '{print $1}' data.lst 

Input:

Bama     2   5 Bama     2   5.001 Bama     2   5.002 Bama     2   5.003 Bama     2   5.004 Bama     2   6 Bama     2   6.003 Bama     2   6.004 Bama     2   4.905 

Output in either case:

Bama     2   5 Bama     2   5 Bama     2   5 Bama     2   5 Bama     2   5 Bama     2   6 Bama     2   6 Bama     2   6 Bama     2   4 
like image 35
Smeterlink Avatar answered Oct 21 '22 15:10

Smeterlink