Reputation: 149
I have two text files. One file with some data like
hi
how
and another file like
L_ hello hi whats up
N_ david
N_ jhon
N_ abraham
N_ mc D
L_ hey how u doing
N_ david
N_ jhon
N_ abraham
N_ mc D
L_ some blah blah blah
N_ david
N_ jhon
N_ abraham
N_ mc D
How can I take a line from the first file and check for presence of this line in the other file?
If the line is present (e.g. hi
in my example) I need to print only that search string and the names just below that line. Consider L_
is some identifier for line where we check for the string if the string is present in that line I want to print the name just below that line with identifier N_
and not the other ones, while printing the identifiers L_
and N_
should be removed.
I am looking for advice on how to solve this using Perl.
Upvotes: 0
Views: 112
Reputation: 50637
perl -ne'
BEGIN{
$x = pop;
($re) = map qr/$_/, join "|", map /(\w+)/ && qr/\Q$1/, <>;
@ARGV = $x;
}
$b = /($re)/ and print("\n$1"),next if /^L_/;
chomp; s/^\w+_//;
print if $b
' file1 file2
output
hi david jhon abraham mc D
how david jhon abraham mc D
Upvotes: 1
Reputation: 53478
You probably want to be looking at the perl functions open and grep.
my $datafile = "some_data_file.txt";
my $comparefile = "data_to_compare.txt";
open ( my $data_filehandle, "<", $datafile ) or die $!;
my @things_to_find = <$data_filehandle>;
open ( my $compare_filehandle, "<", $comparefile ) or die $!;
while ( my $line = <$compare_filehandle> )
{
foreach my $thing ( @things_to_find )
{
print "Match found with: $line" if $line =~ m/$thing/;
print "Next line is :", <$compare_filehandle>;
}
}
That'll pull out the lines that match the pattern, and then print the following line. I'll leave you to figure out the details of parsing each line. The perl documentation on perlre
will help you here.
Upvotes: 0
Reputation: 15121
Try this one:
#!/usr/bin/perl
use strict;
use warnings;
open my $patterns, '<', "$ARGV[0]"
or die "Cannot open $ARGV[0]:$!";
open my $data, '<', "$ARGV[1]"
or die "Cannot open $ARGV[1]:$!";
my @patterns;
while (<$patterns>) {
chomp;
push @patterns, $_;
}
my $line;
LINE: while ($line = <$data>) {
chomp $line;
if ($line =~ m/^\s*L_/) {
foreach my $pat (@patterns) {
if ($line =~ m/$pat/) {
print "$line\n";
while ($line = <$data>) {
if ($line =~ m/^\s*N_/) {
print $line;
}
else {
redo LINE;
}
}
}
}
}
}
Upvotes: 0