How to remove brackets () around ip address from traceroute output

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.


Solution 1:

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

Solution 2:

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 '()'

Solution 3:

Do:

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

Solution 4:

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

Solution 5:

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