#!/usr/bin/perl use strict; use warnings; use Net::Subnet; my $matcher = subnet_matcher qw(192.168.1.0/22); while ( ) { my @ips = m/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/g; next unless @ips; next unless grep { $matcher->($_) } @ips; print; } __DATA__ Sample output that I want to achieve: 2017-12-08 07:01:39 127.0.0.1 GET /course-detail.aspx id=66&catColor=0 443 - 127.0.0.1 (e.g., IP) 200 0 0 530 2017-12-08 07:01:39 127.0.0.1 GET /course-detail.aspx id=66&catColor=0 443 - 192.168.1.2 (e.g., IP) 200 0 0 530 2017-12-08 07:01:39 127.0.0.1 GET /course-detail.aspx id=66&catColor=0 443 - 192.168.2.1 (e.g., IP) 200 0 0 530 2017-12-08 07:01:39 127.0.0.1 GET /course-detail.aspx id=66&catColor=0 443 - 192.168.1.3 (e.g., IP) 200 0 0 530 2017-12-08 07:01:39 127.0.0.1 GET /course-detail.aspx id=66&catColor=0 443 - 192.168.4.3 (e.g., IP) 200 0 0 530 #Note that I only want to grep IP addresses (192.168.1.1-3) that are in the same netmask specified in $matcher