【问题标题】:how to combine cut command with arithmetic comparison如何将剪切命令与算术比较结合起来
【发布时间】:2014-08-25 08:38:24
【问题描述】:

大家早上好,

我有一个名为test.txt的文件

audit.log.20140612:6/11/14 6:27:33 AM;SUCCESS;998ms;10.62.172.52;52750;Issue
audit.log.20140612:6/11/14 6:28:25 AM;SUCCESS;580ms;10.62.172.52;52750;Issue;
audit.log.20140612:6/11/14 6:28:25 AM;SUCCESS;500ms;10.62.172.52;52750;Issue;
audit.log.20140612:6/11/14 6:28:25 AM;SUCCESS;58ms;10.62.172.52;52750;Issue;

现在我想提取所有超过 100 毫秒(毫秒)的行。

我实现了,直到获得命令后的第三个字段形式,

cut -d ';' -f 3 test.txt

现在我想将此结果通过管道传输到某个 shell 命令,以便我可以比较结果。 time is > 100ms

最后我的输出应该是,

audit.log.20140612:6/11/14 6:27:33 AM;SUCCESS;998ms;10.62.172.52;52750;Issue
audit.log.20140612:6/11/14 6:28:25 AM;SUCCESS;580ms;10.62.172.52;52750;Issue;
audit.log.20140612:6/11/14 6:28:25 AM;SUCCESS;500ms;10.62.172.52;52750;Issue;

【问题讨论】:

  • 在 shell 中不可能?

标签: shell awk cut


【解决方案1】:

awk:

awk -F';' '$3+0 > 100' yourfile

bash:

#!/bin/bash                                      
while read line; do 
        fields=(${line//;/ });
        t=${fields[4]}; 
        if [ ${t%ms} -gt 100 ]; 
        then 
                echo "$line"; 
        fi; 
done< yourfile

【讨论】:

  • 比较时会将58ms 转换为58。之后就可以进行算术比较了。
  • 比我想出的要优雅和紧凑得多:awk -F';' '{time=substr($3,match($3,/[0-9]+/),RLENGTH); if(int(time) > 100){ 打印 $0; } }' test.txt
  • +0 经常出现在awk 命令中,用于从字段中提取数字。但如果文本位于像more76 这样的数字前面,则它不起作用。您可以使用sub(/[[:alpha:]]*/,"",$1 删除文本。
  • @run,也更新了bash 解决方案。
猜你喜欢
  • 2010-11-18
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2022-10-15
相关资源
最近更新 更多