2015-07-10 76 views
1
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); 
+2

'perl的-lane '說$ F [1]當m/^ ABC /'' – jm666

+0

@ jm666 我期待爲此寫一個腳本..在我提取這個單詞之後,我還有其他事情要做。所以我試圖寫入一個腳本來調用輸入文件並在提取單詞 – SKG

+0

後將其保存爲輸出。如果m/^ abc/** **是腳本,則說'$ F [1]。由於這些標誌,它由一些其他代碼包裝。你可以在[perlrun](http://perldoc.perl.org/perlrun.html)中瞭解它們。另外,你可以使用'perl -MO = Deparse -lanE'說$ F [1] if/^ abc /''來查看它。 – jm666

回答

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; 
相關問題