Reputation:
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
Reputation: 124
Try this regex instead
/\s*\Q$ip\E\s*$/
\s* matches 0 or more whitespace chars
Upvotes: 0
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
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