【问题标题】:Print specific number from string via AWK/SED通过 AWK/SED 从字符串中打印特定数字
【发布时间】:2017-01-16 10:01:30
【问题描述】:

我有一个大文件,我需要从中提取特定值。我正在寻找带有“Brontes”字样的字符串以及服务启动的时间。

2016-09-05 11:23:08,022 ERROR [xxx.xxx.xx] (MSC service thread 1-6) XXXX015875: XXXX AS 7.1.1.Final "Brontes" started (with errors) in 275637ms - Started 1221 of 1307 services (3 services failed or missing dependencies, 71 services are passive or on-demand)

我试图这样打印:

awk '/Brontes/{print $18}' file

结果正确:275637ms

但是当字符串看起来略有不同(列数改变)时,结果将不一样。

如何实现相同的结果,但不依赖于列数量?

【问题讨论】:

  • 为此,我们需要您提供minimal reproducible example。仅一个示例不足以了解此日志的写入方式
  • 如果您的号码总是以ms 结尾,您可以使用它...grep -oP '\d+ms' file
  • 是的,它总是以 ms 结尾,但是这个 grep 返回所有带有 ms 的值,我只需要其中包含“Brontes”字样的字符串。

标签: awk sed


【解决方案1】:

示例输入:

echo $ola
2016-09-05 11:23:08,022 ERROR [xxx.xxx.xx] (MSC service thread 1-6) XXXX015875: XXXX AS 7.1.1.Final Brontes started (with errors) in 275637ms - Started 1221 of 1307 services (3 services failed or missing dependencies, 71 services are passive or on-demand)

使用 awk 的解决方案:扫描每一列并打印其中包含 ms 的列。

echo $ola |awk '/Brontes/{for(i=1;i<=NF;i++) if( $i ~ /[0-9]+ms/) print $i}'
275637ms

【讨论】:

    【解决方案2】:
    grep -oP 'Brontes.* \K\d+ms' file
    

    这会从包含该数字之前的字符串Brontes 的行中打印所有以ms 结尾的数字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2017-02-15
      相关资源
      最近更新 更多