首页 > 解决方案 > 使用 Bash 从 traceroute 中提取毫秒数,用于以后的数据处理(使用 Python)

问题描述

我想提取 traceroute 在 Linux(版本 2.0.21)中生成的跃点的所有毫秒值。我想要的预期输出如下:

xx
xx
xx
xx

其中 xx 表示traceroute 执行中每一跳的毫秒数,之前或之后没有空白字符。作为参考,示例纯traceroute输出:

2  100.66.0.254 (100.66.0.254)  13.592 ms 100.66.0.208 (100.66.0.208)  15.711 ms 100.66.0.216 (100.66.0.216)  21.187 ms
3  100.66.0.21 (100.66.0.21)  21.266 ms 100.66.0.31 (100.66.0.31)  21.223 ms 100.66.0.29 (100.66.0.29)  21.183 ms

我尝试的解决方案是此代码不适用于所有traceroute输出。

(输入)

traceroute adomain.com | awk '!/traceroute/ {print $4;'}

该字段$4并不总是毫秒值,具体取决于跃点特性。请看下面:

(输出)

13.592
21.266
(xxx.xxx.xxx.xxx) <- Denotes when $4 is not a timestamp.
(xxx.xxx.xxx.xxx)
*
*

(xxx 用来乱码有问题的 IP)。

所以,在上面你可以看到,对于最后四个条目,我没有得到毫秒值。

有没有 awk 或 sed 解决方案?

PS 我将这个发布在 StackOverflow 上,因为这个任务是数据收集任务的一部分,并且数据将在更宏大的编程环境中使用。

标签: bashawk

解决方案


编辑:添加一个解决方案,以防任何人也想在单行中获得多毫秒的输出,然后可以尝试关注。

awk '
{
  while(match($0,/[0-9]+\.[0-9]+ ms/)){
    print substr($0,RSTART+3,RLENGTH-6)
    $0=substr($0,RSTART+RLENGTH)
  }
}
' Input_file


由于您没有显示确切的示例输出,因此仅根据您的解释提供此命令。

traceroute adomain.com |\
awk 'match($0,/[0-9]+\.[0-9]+ ms/){print substr($0,RSTART+3,RLENGTH-6)}'

说明:为上述代码添加详细说明。

awk '                                    ##Starting awk program from here.
match($0,/[0-9]+\.[0-9]+ ms/){           ##Using match with regex to match digits DOT digits space ms in a line.
  print substr($0,RSTART+3,RLENGTH-6)    ##If a match if found then RSTART, RLENGTH variables are SET(which are default awk variables).
                                         ##Then I am printing sub-string which starts from RSTART+3 till value of RLENGTH-3
}
'  Input_file                            ##Mentioning Input_file name here.

推荐阅读