想要提取每行中的第一个单词并将其保存在输出文件中

时间:2015-07-10 18:49:20

标签: perl

abc1 17898 8779 
abc1 68579 7879
abc2 78794 8989
abc2 97857 9897
abc3 79850 9905

.
.
.

abc120  84889 9897  
abc121  87898 7879
abc121  87898 7879 
abc121  87898 7879 
abc122  87898 7879  
abc122  87898 7879

需要帮助..我想从每一行以abc开头并保存它们       在输出文件中。

#!/usr/bin/env perl

use warnings;
open (tran_file, "in.txt" );
open (OUT, " > out.txt");
$count = 0;

 while ($line = <tran_file>)
 {
chomp ($line);

if ($line =~ m/^abc\d*/)    
### matching the word abc.
    {     

     if ($line =~ /\s(\d*)\s+\s(\d+\.\d+)\s+\s(\d+\.\d+)\s(.+)/)
          ### trying to divide the content in the line and extract the 
          word in all the lines ie., abc1, abc2, ...    

            {
                print OUT " $1 \n";

                  ### to print it in the output file
            }
     }
  }
  close (tran_file);

1 个答案:

答案 0 :(得分:1)

         open (tf, "in.txt" );

         open (OUT, " > out.txt");

        while ($line = <tf>)

        {

          my @names = split / / , $line;

            my $out = $names[0];

            print  OUT " $out \n ";
        }
      close(tf);

添加了一些修正后的代码:

use strict;
use warnings;
use autodie;

open my $ifh, '<', 'in.txt';
open my $ofh, '>', 'out.txt';
while( my $line = <$ifh> ) {
        my @fields = split / /, $line;
        print $ofh $fields[0], "\n";
}
close $ifh;
close $ofh;