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

traceroute -m2 |grep .net |awk '{print $3}'

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


8 Answers 8


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

$ traceroute -m 2 | awk '/net/{gsub(/\(|\)/,"");print $3}'    
  • /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

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

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


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

No love for grep/sed?

  • grep with PCRE (-P):

    traceroute -m 2 | 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 | 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

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

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.


This answer is excessively simple.

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


traceroute -m2 |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.


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 | 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"

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.