CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
basic formula for grep one file with contents of another

 



regex2012
User

Nov 2, 2015, 10:37 AM

Post #1 of 2 (1385 views)
basic formula for grep one file with contents of another Can't Post

Actually, if anyone wants to offer simpler suggestions, please do -but I did find out how to do this by google - you can use a hash.


Code
#!/usr/bin/perl 

use strict;

open FILE1, "< /tmp/completed.txt" or die "could not open file1\n";
my $keyRef;
while (<FILE1>) {
chomp;
$keyRef->{$_} = 1;
}
close FILE1;

open FILE2, "< /tmp/list.txt" or die "could not open file2\n";
while (<FILE2>) {
chomp;
my ($Key, $a, $count) = split("\t", $_);
if (defined $keyRef->{$Key}) {
print STDOUT "$_\n";
}
}
close FILE2;



In bash I am able to do

cat /tmp/contents.txt |grep $element

contents.txt
filex
recordz
record5

$element = recordz

This would pull the lines out of the contents.txt file that were in $element. $element contains lines that I am trying to grep for that were in another file.
I am not sure how to do this in perl - is there a quick suggestion?

I have something like this for a start - I want to grep for elements of list.txt in completed.txt:

Code
#!/usr/bin/perl 
use strict;

my $file = "/tmp/completed.txt";
open (FH, "< $file") or die "Can't open $file for read: $!";
my @lines;
while (<FH>) {
push (@lines, $_);
}
close FH or die "Cannot close $file: $!";

print @lines; # see if it worked

my $file = "/tmp/list.txt";
open (FH, "< $file") or die "Can't open $file for read: $!";
my @strings;
while (<FH>) {
push (@strings, $_);
}
close FH or die "Cannot close $file: $!";

print @strings; # see if it worked
foreach $_ (@strings) {
my @array2 = grep {@strings } (@lines);
print FILE "@array2";
close(FILE);
}



(This post was edited by regex2012 on Nov 2, 2015, 11:42 AM)


BillKSmith
Veteran

Nov 2, 2015, 2:16 PM

Post #2 of 2 (1369 views)
Re: [regex2012] basic formula for grep one file with contents of another [In reply to] Can't Post

Keep the hash. Replace the second loop with grep.

Untested:

Code
#!/usr/bin/perl  
use strict;
use warnings;

my $file = "/tmp/completed.txt";
open my $FH, '<', $file or die "Can't open $file for read: $!";
my %keys;
while (<$FH>){
chomp;
$keys{$_} = 1;
}
close $FH or die "Cannot close $file: $!";


$file = "/tmp/list.txt";
open $FH, '<', $file or die "Can't open $file for read: $!";
my @array2 = grep {defined $keys{(split /\t/)[0]}} <$FH>;
close $FH or die "Cannot close $file: $!";

$" = "\n";
print "@array2\n";

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives