Last active
July 31, 2016 09:55
-
-
Save akirad/7fbd917ee29afca660501948289bf46b to your computer and use it in GitHub Desktop.
A perl script which finds strings of file1(fromFile) against file2(toFile).
This file contains hidden or 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
use strict; | |
use warnings; | |
use Getopt::Long; | |
my $notExist = 0; | |
my $fromFile; | |
my $toFile; | |
GetOptions( | |
'notExist' => \$notExist, | |
'fromFile=s' => \$fromFile, | |
'toFile=s' => \$toFile, | |
) or die 'Usage: findStr.pl {-f|fromFile} <Keyword file> {-t|toFile} <target file> [-n|notExist]'; | |
open(my $fromFh, "< $fromFile") or die "Can't open $fromFile: $!"; | |
open(my $toFh, "< $toFile") or die "Can't open $toFile: $!"; | |
while (my $checkLine = <$fromFh>) { | |
next if ($checkLine =~/^#/); | |
chomp($checkLine); | |
my $found = 0; | |
while (my $tgtLine = <$toFh>) { | |
next if ($tgtLine =~/^#/); | |
# I should't use regular expressions here. | |
my $checkLineQuoted = quotemeta($checkLine); | |
# If $tgtLine has a pattern of $checkLineQuoted. | |
if ($tgtLine =~/$checkLineQuoted/) { | |
$found = 1; | |
last; | |
} | |
} | |
# Perl keeps a position of $toFh even if a while loop ends, so it is necessary to seek the position to the begining of the target file. | |
seek($toFh, 0, 0); | |
if ($notExist) { # Not found string. | |
if ($found == 0) { | |
print "$checkLine\n"; | |
} | |
} | |
else { # Found string. | |
if ($found != 0) { | |
print "$checkLine\n"; | |
} | |
} | |
} | |
close($fromFh); | |
close($toFh); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment