in reply to Dealing with large files in Perl
if value exist in file1 and found in file2 than take both lines containing that value and merge into one single fileBut there's nothing in your code to support this kind of operation. What is the value that you're looking for in the two input files?
It looks like both input files are lists of table-like data, with three fields per line ("id up down"). If the value you're looking for is unique to one "cell" in each table (that is, it would occur only once per input file, if at all), then you're really talking about doing a "grep" operation. In fact, if you're using a unix-like OS, just use the "grep" command-line utility; if you're using MS-Windows, there are versions of grep available for free.
But if you want to see how it's done in perl, here's one way:
Now, if you were to try using the unix "grep" command, it would be:#!/usr/bin/perl use strict; my $Usage = "Usage: $0 value file1 file2\n"; die $Usage unless ( @ARGV == 3 and -f $ARGV[1] and -f $ARGV[2] ); my $value = shift; # removes first element from @ARGV my @match; # will hold matching line from each file for my $file ( @ARGV ) { # loop over remaining two ARG's open( IN, $file ) or die "$file: $!"; while (<IN>) { if ( /$value/ ) { chomp; push @match, $_; last; } } } print join( " ", @match ), "\n";
Note that both the perl script and the grep command shown above will output the matching lines to STDOUT (the grep command will not join the two into a single line -- it will also include the file name at the beginning of each line, to show where the line came from).grep value file1 file2
Also, your output might not be what you expect, if the value you're searching for contains characters that have special meanings in a regex (period, plus-sign, asterisk, question mark, brackets, braces, parens, "^", "$", "@" or "%", some others, depending on context). For such things, put "\Q" and "\E" around $value in the perl script.
If you want the matches to be saved in a separate file, just use redirection on the command line:
perlscript value file1 file2 > matched.lines # or grep value file1 file2 > matched.lines
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Dealing with large files in Perl
by tester786 (Initiate) on May 16, 2005 at 05:38 UTC | |
by graff (Chancellor) on May 16, 2005 at 21:43 UTC | |
by tester786 (Initiate) on May 17, 2005 at 20:02 UTC | |
by tester786 (Initiate) on May 23, 2005 at 23:24 UTC | |
by jZed (Prior) on May 23, 2005 at 23:33 UTC | |
by tester786 (Initiate) on May 26, 2005 at 06:12 UTC |