简体   繁体   English

awk数值比较

[英]awk numeric comparison

I am confused with the awk return code... 我对awk返回码感到困惑...

Command : 命令:

cat /etc/redhat-release |awk '{print $3 >= 6.5;}'

result : 1 (should be 0 or I am looking for 0) 结果:1(应为0或我正在寻找0)

Here is my file /etc/redhat-release 这是我的文件/ etc / redhat-release

cat /etc/redhat-release ->
CentOS release 6.5 (Final)

I am bit confused with this... 我对此感到困惑...

Help ...! 救命 ...!


cat /etc/redhat-release |awk '{print $3 >= 6.5}'

1

cat /etc/redhat-release |awk '{print $3}'

6.5 

Your confusion may stem from the result you are expecting from a true or false comparison. 您的困惑可能源于对真或假比较的预期结果。

From the gawk manual; 来自gawk手册;

In awk, any nonzero numeric value or any nonempty string value is true. 在awk中,任何非零数字值或任何非空字符串值均为true。 Any other value (zero or the null string, "") is false. 其他任何值(零或空字符串“”)均为false。

In other words, if the field is not "0" or "", it is true. 换句话说,如果该字段不是“ 0”或“”,则为true。 So if you are looking for (expecting) a 0, you are expecting the comparison to be false. 因此,如果您正在寻找(期望)0,则期望比较是错误的。

The following may help you control your comparisons, but still won't make "0" the result of a true comparison. 以下内容可能会帮助您控制比较,但仍不能使“ 0”成为真正比较的结果。

To force a field value into a numeric context, you can add zero or multiply by one. 要将字段值强制为数字上下文,可以加零或乘以1。 ($3 + 0) or ($3 * 1) before comparing to a numeric value. ($ 3 + 0)或($ 3 * 1),然后与数值进行比较。 To force a field value into a string context, you can concatenate with an empty string. 要强制将字段值放入字符串上下文中,可以连接一个空字符串。 Remember awk uses white space to concatenate. 请记住,awk使用空格进行连接。 ($3 "") ($ 3“”)

Looks like your intention is to print the whole line when the version (field 3) is >= 6.5. 看起来您的意图是在版本(字段3)> = 6.5时打印整行。 In an awk expression, the condition should precede action, like this (no need for cat ... | ): awk表达式中,条件应在动作之前,例如这样(不需要cat ... | ):

awk '$3 >= 6.5 {print}' /etc/redhat-release

since print is the default action, just awk '$3 >= 6.5' /etc/redhat-release would suffice (as Inian pointed out). 因为print是默认操作,所以只要awk '$3 >= 6.5' /etc/redhat-release就足够了(正如Inian指出的那样)。

The command 命令

awk '{print $3 >= 6.5}' /etc/redhat-release

gives the output of 1 which is the value of expression, as $3 >= 6.5 evaluates to true. 给出输出1 ,它是表达式的值,因为$3 >= 6.5计算为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM