2016-07-23 42 views
-3

我試圖使用perl從目錄輸出中的所有文本文件中提取特定字段到一個新文件,每個文本文件放在一個新行中。提取特定字段並與perl合併爲1個文本文件

輸入

#Sample = xxxxx 
#Sample Type = xxxxxx 
#Build = xxxxxxx 
#Platform = xxxxxxx 
#Display Name= XXXXX (keep this field without the #) 
#identifier = xxxxxx (keep this field without the #) 
#Gender = xxxxx  (keep this field without the #) 
#Control Gender = xxxxx 
#Control Sample = xxxxx 
#Quality = X.XXXXXX (keep this field without the # and X.XXX) 

所需的輸出(字段,每個文本文件保存)

Display Name= XXXXX (keep this field without the #) 
identifier = xxxxxx (keep this field without the #) 
Gender = xxxxx  (keep this field without the #) 

我把@Borodin建議在以前的帖子,並試圖腳本來實現這一點我認爲是接近的:

perl

#!/bin/perl 
use strict; use warnings; 
perl -ne '(s/^#(Display Name|identifier|Gender)/$1/ or s/^#(Quality = \d\.\d{3})\d+/$1/) and print' *.txt > all.txt 
perl "C:\cygwin\home\get_all_qc2.pl" 
syntax error at C:\cygwin\home\get_all_qc2.pl line 3, near "-ne" 
Execution of C:\cygwin\home\get_all_qc2.pl aborted due to compilation errors. 

謝謝:)。

+1

你在你的Perl腳本中編寫了命令行perl調用? – Ven

+1

你知道任何Perl嗎? – melpomene

+0

是的,我用'perl「C:\ cygwin \ home \ get_all.pl」'謝謝你:)來調用它。 – Chris

回答

2

好的,首先,如果您將此代碼作爲.pl文件中的腳本運行,那麼您做錯了。你所做的是將一行Perl的shell調用寫入你的文件,並期望它作爲Perl代碼執行!

因此,要啓動,我們會將您的文件來是這樣的:

#!/bin/perl 
use strict; use warnings; 
s/^#(Display Name|identifier|Gender)/$1/ or s/^#(Quality = \d\.\d{3})\d+/$1/) and print; 

然後我們只是perl file.pl調用它。

但實際上並沒有做到你想要的。

所以,相反,我們做這樣的事情:

#!/bin/perl 
use warnings; use strict; # Good Perl practice to use these, always 

my $file = $ARGV[0]; # Grabs the filename from the cmdline arguments 
open my $fh, '<', $file or die "Cannot open $file: $!"; # Opens the file 

while (my $line = <$fh>) { 
    $line =~ /\#(?:((?:Display Name|Identifier|Gender) = .+)|(Quality =))/; # Match and capture your desired elements 
    print $1 if ($1); # If we found anything, print it 
} 

close $fh; 

然後我們用perl file.pl input.txt執行它,坐下來,並讓它運行。

+1

謝謝@Sebastian Lenartowicz ...我熟悉shell環境,這是我的問題的一部分,以及如何最好地使用'perl'方法。我非常感謝你的幫助和解釋:) – Chris