code_junkie

Searching/reading another file from awk based on current file's contents, is it possible?

Nov 11th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. f1 f2 f3 f4 f5
  2. X Y Z A B
  3.  
  4. f1 f2 f3 f4
  5. A U B W
  6.  
  7. #!/usr/bin/env perl -nwa
  8. use strict;
  9. use File::Find 'find';
  10. my @search = qw(X Y Z);
  11.  
  12. # if you know in advance that the otherfile isn't
  13. # huge, you can cache it in memory as an optimization.
  14.  
  15. # with any more columns, you want a loop here:
  16. if ($F[0] eq $search[0]
  17. and $F[1] eq $search[1]
  18. and $F[2] eq $search[2])
  19. {
  20. my @files;
  21. find(sub {
  22. return if not -f $_;
  23. # verbatim search for the columns in the file name.
  24. # I'm still not sure what your file-search criteria are, though.
  25. push @files, $File::Find::name if /Q$F[3]E/ and /Q$F[4]E/;
  26. # alternatively search for the combination:
  27. #push @files, $File::Find::name if /Q$F[3]E.*Q$F[4]E/;
  28. # or search *all* files in the search path?
  29. #push @files, $File::Find::name;
  30. }, '/search/path'
  31. )
  32. foreach my $file (@files) {
  33. open my $fh, '<', $file or die "Can't open file '$file': $!";
  34. while (defined($_ = <$fh>)) {
  35. chomp;
  36. # order of fields doesn't matter per your requirement.
  37. my @cols = split ' ', $_;
  38. my %seen = map {($_=>1)} @cols;
  39. if ($seen{$F[3]} and $seen{$F[4]}) {
  40. print join(' ', $F[0], @cols[1,2]), "n";
  41. }
  42. }
  43. close $fh;
  44. }
  45. } # end if matching line
  46.  
  47. ## perl code to do some dirty work
  48.  
  49. for my $line (`grep 'X Y Z' myhugefile`) {
  50. chomp $line;
  51. my ($a, $b, $c, $d, $e) = split(/ /,$line);
  52. my $cmd = 'grep -P "' . $d . ' .+? ' . $e .'" otherfile';
  53. for my $from_otherfile (`$cmd`) {
  54. chomp $from_otherfile;
  55. my ($oa, $ob, $oc, $od) = split(/ /,$from_otherfile);
  56. print "$a $ob $ocn";
  57. }
  58. }
Add Comment
Please, Sign In to add comment