Parsing data from traceroute command

谁都会走 提交于 2019-12-02 04:11:44

Are you looking for the number of hops it took, or the "64 hops max" value? If it's the former, use tail to get the last line of output, then awk to print the first column:

traceroute "$hostname" 2>/dev/null | tail -1 | awk '{print $1}'

The only occurrence of "hops" in traceroute output (stderr, actually) is towards the top, in the stderr "header" line:

traceroute to foo.bar.com (123.12.1.23), 30 hops max, 40 byte packets

or the like -- if that's the one line you want to grab, you might grep for "hops max," or the like in order to reduce the risk of undesired hits (should some intermediate host just happen to have "hops" in their DNS).

Is this what you mean? Is your problem grabbing this 30, the maximum number of hops, into a bash variable? If that's so, then

maxhops=`traceroute www.yahoo.com 2>&1 >/dev/null | grep "hops max" | cut -d' ' -f5`

should help -- you can use $maxhops after this (and it will be 30 in the above example).

But I suspect you mean something completely different -- clarify, maybe...?

Edit: the OP has clarified they want, not maxhops, but the actual number of hops as measured by traceroute; for that purpose,

numhops=`traceroute www.yahoo.com 2>/dev/null | tail -1 | cut -d' ' -f2`

or a simpler

numhops=`traceroute www.yahoo.com | wc -l`

should work fine!

If you do want anything fancier (or more than one result, etc) then awk as suggested in other answers is perfectly fine, but a pipeline mix of grep, tail, and cut, is quite a traditional unix-y approach, and still quite workable for simple cases (and some complex ones, but awk or perl may be more appropriate for those;-).

traceroute www.google.com 2>/dev/null | awk 'NR==1{print $5;exit}'
ghostdog74

another way, where those hops not reachable (for lack of better word) are not counted

# traceroute www.yahoo.com 2>/dev/null | awk 'NR>1 && !/* * */{c++}END{print c}'
  16
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!