2011-04-27 188 views
14

我正在尋找一種在awk中將字符串強制轉換爲int的方法。我有這似乎是做一個字符串比較在awk中強制轉換爲int

以下(:場$ 5是兩種格式之一的百分比; 80%或9.0%)

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

所以當我將其更改爲:

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

它比較像我預期的。這是合適的演員嗎?是否有更好的方法來演員演員?

+0

爲什麼+0,爲什麼不是$ 5 + 0還是不行? – HattrickNZ 2016-05-10 03:02:07

回答

13

您可以使用+0。說變量v是你的百分比值。

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

您不必擺脫%標誌。

15

大多數新awks有一個int()函數。

但是當你做到這一點,利用numericValue和+0顯示在「awk編程語言中」鑄造記錄的方法。我沒有這本書的方便,但我認爲你也可以使用+0.0來鑄造浮動值。

我希望這會有所幫助。

0

the docsint(x) POSIX兼容。該數字仍然是一個浮點數(因爲awk中的所有數字都是浮點數),但它將被截斷爲int。


添加0不會將字符串轉換爲int。它會將其轉換爲浮點數。

如果由Brian Kernighan的基礎上The One True AWKawk,如macOS awkFreeBSD awk,你會看到this在手冊頁的底部:

BUGS 
    There are no explicit conversions between numbers and strings. To force 
    an expression to be treated as a number add 0 to it; to force it to be 
    treated as a string concatenate "" to it. 

    The scope rules for variables in functions are a botch; the syntax is 
    worse. 

要強制表達被視爲一些加0它


如果你不關心花車和你有gawk你也可以使用strtonum


其它來源:

OS X version of AWK, which is derived from "The One True AWK」 by Brian Kernighan

所有號碼awk是浮點:

Search "All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard"

Search "all numbers in awk are floating"

相關問題