Regex Question: Only print part of line that matches
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Regex Question: Only print part of line that matches
Greetings,
Overview: I need to be able to use a regular expression to display only parts of a line that match the expression.
Input: A file that is filled with error messages from different hosts. Each line has an error message and the IP address that caused the error.
Desired Output: A list of all the IP addresses found in the file.
Here is what I have currently. It returns the proper lines, but I only want to print the part of the line that matches, so I end up with a list of IP addresses only. The IP address could be located anywhere in the line so I cant use something like awk to just print the proper field - it will be different for each returned line.
Here is a perl script I wrote a while back. It actually prints the ips and how many times they appear, but you should be able to alter it to suit your needs. You can put your input file(s) as an argument or feed whatever input to stdin.
Code:
#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Long;
my $thresh = 0;
my $comma;
my %ips;
GetOptions(
"threshold=i" => \$thresh,
"comma" => \$comma,
) or die "Options problem";
while (<>) {
if (m[((\d{1,3}\.){3}\d{1,3})]) {
$ips{$1}++;
}
}
foreach my $ip (keys %ips) {
next unless $ips{$ip} > $thresh;
if ($comma) {
print ",$ip";
} else {
printf "%-18s - %5d\n", $ip,$ips{$ip};
}
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.