bash - 使用 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 上,因为这个任务是数据收集任务的一部分,并且数据将在更宏大的编程环境中使用。
解决方案
编辑:添加一个解决方案,以防任何人也想在单行中获得多毫秒的输出,然后可以尝试关注。
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.
推荐阅读
- javascript - 如何将变量传递给运行内联 Javascript 的 Rails?
- python - 在迁移学习中,我们可以改变输入大小吗?
- node.js - 每次我想创建一个反应应用程序时都会收到这个错误:
- arduino - 如何连接 Arduino nano 33 IOT 和 PN532 模块?
- python - Python open() 给出“FileNotFoundError: [Errno 2] No such file or directory:”,但文件存在
- python - Pytorch:能不能让一个没有bias的卷积模块再有bias?
- javascript - Tippy.JS“TypeError:instance.setContent 不是函数”
- python - 如何减去两个列表,其中一个列表包含来自重采样方法的值,另一个列表包含数据框中的正常值?
- c++ - 井字游戏板值没有改变
- phpmyadmin - 在“sudo nano /etc/apache2/apache2.conf”里面插入“Include /etc/phpmyadmin/apache.conf”。当我在“sudo apache2ctl restart”中输入这个