通过AWK / SED从字符串打印特定号码

时间:2016-09-08 12:51:34

标签: awk sed

我有大文件,我需要从中提取特定值。我在找" 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

但是当字符串看起来略有不同(列数量发生变化)时,结果将不相同。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

grep -oP 'Brontes.* \K\d+ms' file

这将打印包含字符ms的行之前以Brontes结尾的所有数字