Created
August 21, 2012 14:59
-
-
Save MinCha/3416270 to your computer and use it in GitHub Desktop.
Extract pattern from file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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