Reputation: 4378
I'm writing a script to perform some basic regular expression matching on Linux's netstat
command. My regex works fine and gets me the columns I want in five groups: the protocol and two pairs of IP addresses and port numbers.
I then run a global match on my regex against netstat's output and iterate across the resulting array to print the information in a few columns:
my $content = `netstat -na`;
my $REGEX = '([a-z]*) +.* (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5}) +(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5}).*ESTABLISHED';
foreach ($content =~ m/$REGEX/g) {
printf ("%-10s%-18s%-10s%-18s%-10s\n", $1, $2, $3, $4, $5);
}
However this didn't get me the desired result as it only printed the last matching line several times. It didn't take me long to figure out that I was using the number variables $1
through $5
incorrectly: they always refer to the numbered group of the last line that matched a regular expression.
This now leaves me with a problem: I'd like to use the groups I defined in my original regex with the lines that the global match returns. Is this at all possible or is global matching simply a way to perform a grep-like operation?
If there's no way to save these groups while the global match is running or retrieve them from the array afterwards, I'll likely have to give up on the global match and instead iterate across the lines in order to save the groups to a multi-dimensional array. In this case, I'm almost tempted to just pipe netstat
to grep
first...
Upvotes: 1
Views: 120
Reputation: 67900
Try changing foreach
to while
, so that you iterate through the matches one at the time, instead of creating all the matches at once.
while ($content =~ m/$REGEX/g) {
Upvotes: 1