如何比较由 / 分隔的列的值

如何比较由 / 分隔的列的值

我想比较同一列的值/

session-manager-0    3/5    1 >>> want to compare second column value 3 and 5 using awk.
session-manager-1    5/5    1
session-manager-2    5/5    1

答案1

您可以split根据第二个分隔符(例如)来细分字段。

$ awk 'split($2,a,"/") > 1 && a[2] > a[1]+0' file
session-manager-0    3/5    1 >>> want to compare second column value 3 and 5 using awk.
  • ifsplit生成至少 2 个值;和
  • 第二个分割值大于第一个(强制数字比较后)
  • 然后应用默认print规则

答案2

$ awk -F'[[:space:]/]+' '$2 < $3' file
session-manager-0    3/5    1 >>> want to compare second column value 3 and 5 using awk.

答案3

仅使用awk,您需要管理多个匹配(有点类似于您可以在这个帖子)。

这是我的纯awk解决方案:

awk '{
  match($0, /[0-9]+\/[0-9]+/);                      # match number/number pattern
  pattern=substr($0,RSTART, RLENGTH);               # store match in $pattern
  match(pattern, /[0-9]+/);                         # match first number
  num1=substr(pattern,RSTART,RLENGTH);              # store it in $num1
  sub(/[0-9]+\//,"",pattern);                       # remove 'number/' from $pattern
  match(pattern, /[0-9]+/);                         # match second number
  num2=substr(pattern,RSTART,RLENGTH);              # store it in $num2
  if ($num1 > $num2){ print num1, ">", num2 }       # do your comparisons
  else if ($num1 < $num2) { print num1, "<", num2 } # as you please
  else { print num1, "=", num2  }                   # (this is just an example)
  }' file

然而,在这种情况下,我实际上会使用sed来提取两个数值,然后将输出通过管道传输到awk.以下命令与上面的命令相同,但我认为它在功能上更清晰:

sed 's@^.*\([0-9]\+\)\/\([0-9]\+\).*$@\1 \2@' file |
  awk '{if ($1 > $2){ print $1, ">", $2 }
        else if ($1 < $2) { print $1, "<", $2 }
        else { print $1, "=", $2  }}'

相关内容