Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to int in awk

Tags:

I'm looking for a method to cast a string to an int in awk. I have the following which appears to be doing a string comparison

(note: field $5 is a percentage in one of two formats: 80% or 9.0%)

awk '{if (substr($5,1,(length($5)-1)) >= 90) ... 

So, when I change it to:

awk '{if (substr($5,1,(length($5)-1))+0 >= 90+0 ) ... 

It compares as I intended. Is this an appropriate cast? Is there a 'better' way to perform the cast?

like image 246
xelco52 Avatar asked Apr 27 '11 18:04

xelco52


People also ask

How to convert string to number in awk?

To force a string to be converted to a number, add zero to that string. A string is converted to a number by interpreting any numeric prefix of the string as numerals: "2.5" converts to 2.5, "1e3" converts to 1,000, and "25fix" has a numeric value of 25.

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

How do you print on awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

Which of the following is a built in function for awk?

AWK has lots of built-in functions for numeric, string, input, and output operations. Awk has the following two types of high level built-in function categories: Built-in functions for numeric operations. Built-in functions for string operations.


2 Answers

Most new awks have an int() function.

But the method for casting documented in 'The Awk Programming Language' is shown as you do it, by using numericValue and +0. I don't have the book handy, but I think you can also cast for float value by using +0.0.

I hope this helps.

like image 117
shellter Avatar answered Sep 23 '22 14:09

shellter


You can just use +0. say variable v is your percentage value.

$ awk -v v="80.1%" 'BEGIN{print v+0.1}' 80.2 

You do not have to get rid of the % sign.

like image 42
ghostdog74 Avatar answered Sep 22 '22 14:09

ghostdog74