Connecting Tech Pros Worldwide Help | Site Map

Need help combine two simple steps into one. Thanks.

Newbie
 
Join Date: Nov 2006
Posts: 3
#1: Nov 11 '06
Guys and Gals

I need help big time in some simple Perl scripts. Let me explain.

I have two txt files with this type of format:

Text1 file 1
aaa 234 bbb ccc ddd eee fff
bbb 456 asd fsd fsdf fds fdsf
cdc 999 dfs dfl asl asd asd
aaa 999 bbb ccc ddd eee fff
bbb 578 asd fsd fsdf fds fdsf
cdc 346 dfsd dflkj aslk asdlkj asdi

Text file 2
aaa 234 bbb ccc ddd eee fff
bbb 456 asd fsd fsdf fds fdsf
cdc 888 dfs dfl asl asd asd
aaa 888 bbb ccc ddd eee fff
bbb 578 asd fsd fsdf fds fdsf
cdc 346 dfsd dflkj aslk asdlkj asdi

I want the the output to be

cdc 999 dfs dfl asl asd asd cdc 888 dfs dfl asl asd asd
aaa 999 bbb ccc ddd eee fff aaa 888 bbb ccc ddd eee fff

Basically, I want to extract some part of textfile1 and someother part of textfile2 then combine them into another text file3.

I've been doing this using two separate scripts:

while (<STDIN>) {
chomp;
s/^\s+//;
$number1= 999; # or 888
while (<>) {
($col1, $col2, $col3,@rest) = split; #Good but provide no testing

if ($col2 =~ /^\d+$/ & ($col2 =~ $number1)) {
printf ("%s\t %.1lf\t %.1lf\n",$col1,$col2,$col3);
};
};
};

to extract the 888 and 999 part of the two txt files and pipe those into out1.txt and out2.txt

Then I use

$tab = "\t";

open(FILE1, $ARGV[0]) || die "Cannot open $ARGV[0]: $!\n";
open(FILE2, $ARGV[1]) || die "Cannot open $ARGV[0]: $!\n";

#open(FILE1, $ARGV[0]);
#open(FILE2, $ARGV[1]);

while ($line = <FILE1>) {
$line =~ s/\n//;
print STDOUT $line . $tab . <FILE2>
}

and pipe that to the final txt file.

Please show me a better way to do this in one step similar to

perl script input_file2 input_file2 > output.txt

I hope I explain myself rather clear. Thank you
NK
Member
 
Join Date: Nov 2006
Posts: 83
#2: Nov 11 '06

re: Need help combine two simple steps into one. Thanks.


Quote:

Originally Posted by nk215

Please show me a better way to do this in one step similar to

perl script input_file2 input_file2 > output.txt

I'm not sure I understand what the tricky part is. Anyway, this code might help you move forward:
Expand|Select|Wrap|Line Numbers
  1. my @lines;
  2. my $num = qr[^(?:999|888)$];
  3. for my $i ( 0, 1 ) {
  4.     open my $fh, '<', $ARGV[$i] or die $!;
  5.     while ( <$fh> ) {
  6.         chomp;
  7.         ( undef, my $col2, undef ) = split ' ', $_, 3;
  8.         push @{ $lines[$i] }, $_ if $col2 =~ $num;
  9.     }
  10. }
  11. while ( my $line = shift @{ $lines[0] } ) {
  12.     print "$line\t", shift( @{ $lines[1] } ), "\n";
  13. }
  14.  
Reply