Skip to content

Instantly share code, notes, and snippets.

@MinCha
Created August 21, 2012 14:59
Show Gist options
  • Save MinCha/3416270 to your computer and use it in GitHub Desktop.
Save MinCha/3416270 to your computer and use it in GitHub Desktop.
Extract pattern from file
#!/usr/bin/perl
##############################################################################
# $fileName : a filename to analyze
# $pattern : regexp pattern
# $patternIndex : a group index to extract(0..n)
# (OPT)$count : count will be printed if value is 1
##############################################################################
if (@ARGV < 2) {
print("usage : $0 (M)FILE_NAME (M)PATTERN\n");
exit 1;
}
my $fileName = $ARGV[0];
my $pattern = $ARGV[1];
my $patternIndex = $ARGV[2];
$pattern = "(".$pattern.")" unless ($pattern =~ /\(.*\)/);
my $count = $ARGV[3] eq "" ? "0" : $ARGV[3];
open(FH, "$fileName") or die("Failed to open the file '$fileName'.");
while($line = <FH>) {
chomp($line);
my @str = ($line =~ /$pattern/);
my $value = $str[$patternIndex];
if ($nos{$value} eq "") {
$nos{$value} = "1";
} else {
$nos{$value} = $nos{$value} + 1;
}
}
for my $key (sort keys %nos) {
print("'$key'\t$nos{$key}\n") if ($count == 1);
print("$key\n") if ($count == 0);
}
close FH;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment