6

I need to extract the 2nd IP address from a traceroute like so

traceroute -m2 8.8.8.8 |grep .net |awk '{print $3}'
(111.222.333.4444)

No matter what I try I can't seem to work out how to remove the surrounding brackets from the output.

9

You don't need grep in between, use AWK's pattern matching capability.

$ traceroute -m 2 8.8.8.8 | awk '/net/{gsub(/\(|\)/,"");print $3}'             
207.225.112.2
  • /net/ matches lines with the word net
  • gsub( /\(|\)/ , "" ) matches ( or ) and replaces them with empty string ( effectively deleting).
  • print $3 prints the 3rd item which is still the IP address , but without brackets
| improve this answer | |
4

I simply use tr -d to remove a set of characters, it is simpler. And awk can also grep at once:

traceroute -m 2 8.8.8.8 | awk '/.net/{print $3}'  |  tr -d '()'
| improve this answer | |
3

Do:

traceroute -m2 8.8.8.8 | grep .net | awk '{print $3}' | sed -e "s/(//" -e "s/)//"
| improve this answer | |
2

No love for grep/sed?


  • grep with PCRE (-P):

    traceroute -m 2 8.8.8.8 | grep -Po '\.net[^(]+\(\K[^)]+(?=\))'
    
    • \.net[^(]+\( matches the portion before ( and \K discards the match

    • [^)]+ macthes our desired portion within () and zero width positive lookahead (?=\)) ensures the portion is followed by )


  • sed with similar logic:

    traceroute -m 2 8.8.8.8 | sed -nr 's/.*\.net[^(]+\(([^)]+)\).*/\1/p' 
    
    • .*\.net[^(]+\( matches everything before (

    • ([^)]+) is our desired portion in first matched group, we will use it in replacement as \1

    • \).* matches everything else after the desired portion

| improve this answer | |
1
traceroute -m2 8.8.8.8 |grep .net |awk '{print $3}' |cut -d '(' -f2 | cut -d ')' -f1 
| improve this answer | |
1

If your awk allows regexp field separators, use the single command:

awk -F'[()]' '/\.net/{print $2}'

This splits the input into words separated by ( or ), so the 2nd word is the ip address.

| improve this answer | |
1

This answer is excessively simple.

traceroute -m2 8.8.8.8 |grep .net |awk '{print $3}'|cut -f1 -d) -c2-

or

traceroute -m2 8.8.8.8 |grep .net |awk '{print $3}'|cut -f1 -d) -b2-

The first one is preferred for this case, as we're working with characters, not bytes, although the second one might be faster (a little bit of course), as it works directly with bytes. We can use both, because ( is one byte.

| improve this answer | |
1

A friend gave me this solution and I thought I should post it here to maybe help others having a similar problem.

traceroute -w 20 -m 2 8.8.8.8 | egrep "^ 2" | sed -r -e 's/.*\(([^)]*).*/\1/'

Its a much better way of extracting the IP address from the second line of the traceroute output instead of relying on locating "net"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.