Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Match Ip Address on cmd line

by sans-clue (Beadle)
on Sep 09, 2011 at 04:56 UTC ( #925009=perlquestion: print w/replies, xml ) Need Help??
sans-clue has asked for the wisdom of the Perl Monks concerning the following question:

Solaris grep is letting me down and admin rules prevent me from using gnu grep. I have a file that looks myhost 1-4-3-2/0

I'd like to cat to pipe that file and do a perl regex to print only valid ip addresses.

cat file | perl -.......

and the output would in this case be

I looked around and just found entire scripts. thanks

Replies are listed 'Best First'.
Re: Match Ip Address on cmd line
by NetWallah (Canon) on Sep 09, 2011 at 05:13 UTC
    This 'quick and dirty' regex will work reasonably well for "reasonable" data:
    perl -ne 'print qq|$1\n| if m/^\s*((?:\d{1,3}\.){3}\d{1,3})\s*$/'
    It is tolerant of leading and trailing white-space, but does not check for octets being under 255, or being all zero at the first octet. There are "standard regex" Regexp::Common modules that do a more thorough check for IPv4 validity.

                "XML is like violence: if it doesn't solve your problem, use more."

      thanks so much, does the trick. what does qq mean ?

      Also, yes I know this isn't a code writing service, but I could not find an 'if m/...' example in a command line, plus I would have never come up with 2 |'s

        The things you ask about are partly about style choices.


        do_something() if <condition>; if (<condition>) { do_something(); }


        m[regex] m|regex| m/regex/ /regex/


        "string-with-expanded-$variables" qq[string-with-expanded-$variables] qq/string-with-expanded-$variables/
        Using qq// is common on command lines, since the shell itself may require quotes or double-quotes.


        'string-expanding-no-variables' q[string-expanding-no-variables] q/string-expanding-no-variables/
        All of this can be found in perldoc perlsyn and perldoc perlop.

        [ e d @ h a l l e y . c c ]

Re: Match Ip Address on cmd line
by afoken (Abbot) on Sep 09, 2011 at 06:07 UTC

    So, what have you tried, where did you fail? Perlmonks is not a code writing service.

    And by the way: Do you want to match only IPv4 addresses or also IPv6 addresses?


    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: Match Ip Address on cmd line
by zentara (Archbishop) on Sep 09, 2011 at 10:08 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://925009]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2018-06-24 17:10 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.