user1121951
user1121951

Reputation:

perl + match exactly IP ADDRESS but ignore spaces and TABS

the following perl liner code will match exactly the IP address

perl -ne 'BEGIN{$ip=shift(@ARGV);} 
    print if /^\Q$ip\E$/;' "$IP_ADDRESS"  $FILE

the problem is that we cant match by the following perl code if space or TAB before or after the $IP_ADDRESS

please advice what need to add to my code in order to ignore spaces and tabs ?

examples from my linux machine

$ echo "192.9.200.1" |
    perl -ne 'BEGIN{$ip=shift} 
        print if/^\Q$ip\E$/;' "192.9.200.1"
192.9.200.1  ( MATCH )

$ echo " 192.9.200.1" |
    perl -ne'BEGIN{$ip=shift} 
        print if/^\Q$ip\E$/;' "192.9.200.1"
NO MATCH

echo "192.9.200.1 " |
    perl -ne'BEGIN{$ip=shift}
        print if/^\Q$ip\E$/' "192.9.200.1"
NO MATCH

expected results

echo "192.9.200.1 "|
    perl -ne'BEGIN{$ip=shift}
        print if/^\Q$ip\E$/;' "192.9.200.1"
should MATCH

echo "192.9.200.1"|
    perl -ne'BEGIN{$ip=shift}
        print if/^\Q$ip\E$/;' "192.9.200"
should NOT MATCH

echo "192.9.200.1"|
    perl -ne'BEGIN{$ip=shift}
        print if/^\Q$ip\E$/;' "192.9.200."
should NO MATCH

Upvotes: 0

Views: 163

Answers (4)

arunxls
arunxls

Reputation: 124

Try this regex instead

 /\s*\Q$ip\E\s*$/

\s* matches 0 or more whitespace chars

Upvotes: 0

Toto
Toto

Reputation: 91373

Try this one:

print if /(^|\s)\Q$ip\E(\s|$)/;

Upvotes: 1

JRFerguson
JRFerguson

Reputation: 7516

You could use Regexp::Common::net

perl -MRegexp::Common=net -nE 'say +($_=~/^$RE{net}{IPv4}{-keep}$/)?q(MATCH):q(NO MATCH)'
192.9.200.1
MATCH
        192.9.200.1
NO MATCH
    192.999.200.1
NO MATCH

This has the additional advantage of detecting invalid patterns for IP addresses.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

You could trim leading and trailing whitespace first:

perl -ne '
    BEGIN { $ip = shift @ARGV; }
    s/^\s+|\s+$//g;
    print if /^\Q$ip\E$/; 
' "$IP_ADDRESS"  $FILE

Upvotes: 0

Related Questions