2011-03-20 30 views
0

使用perl尋找一個不區分大小寫的搜索,所以如果一個「!」在行的開始處被檢測到,新的排序開始(僅在該部分)。文本文件中的多重排序

[test file] 
! Sort Section 
! 
a 
g 
r 
e 
! New Sort Section 
1 
2 
d 
3 
h 

變,

[test file] 
! Sort Section 
! 
a 
e 
g 
r 
! New Sort Section 
1 
2 
3 
d 
h 
+0

在我的手機自動取款機,我有一個基本的排序會,但無法得到工作 – user349418 2011-03-20 12:51:24

回答

1

再一個,使用一個輸出文件。更重要的是,不加載整個文件到內存:

use strict; 
use warnings; 
sub output { 
    my($lines, $fh) = @_; 
    return unless @$lines; 
    print $fh shift @$lines; # print first line 
    print $fh sort { lc $a cmp lc $b } @$lines; # print rest 
    return; 
} 
# ==== main ============================================================ 
my $filename = shift or die 'filename!'; 
my $outfn = "$filename.out"; 
die "output file $outfn already exists, aborting\n" if -e $outfn; 
# prereqs okay, set up input, output and sort buffer 
open my $fh, '<', $filename or die "open $filename: $!"; 
open my $fhout, '>', $outfn or die "open $outfn: $!"; 
my $current = []; 
# process data 
while (<$fh>) { 
    if (m/^!/) { 
     output $current, $fhout; 
     $current = [ $_ ]; 
    } 
    else { 
     push @$current, $_; 
    } 
} 
output $current, $fhout; 
close $fhout; 
close $fh; 
+0

我注意到unix格式化的文本文件在輸出中變成了dos格式,是否有修復(保持原始文本格式)? ..腳本運行在win32環境下,謝謝:) – user349418 2011-03-21 00:22:52

+0

解決的辦法是在文件句柄上調用'binmode'。 – Lumi 2011-03-21 00:45:21

2

下面是做這件事:

use strict; 
use warnings; 
my $filename = shift or die 'filename!'; 
my @sections; 
my $current; 
# input 
open my $fh, '<', $filename or die "open $filename: $!"; 
while (<$fh>) { 
    if (m/^!/) { 
     $current = [ $_ ]; 
     push @sections, $current; 
    } 
    else { 
     push @$current, $_; 
    } 
} 
close $fh; 
# output 
for (@sections) { 
    print shift @$_; # print first line 
    print sort @$_; # print rest 
} 
+0

章節位跳過不區分大小寫方面。你可以像這樣提供你的排序例程:'print sort {lc $ a cmp lc $ b} @ $ _; #print rest' – Lumi 2011-03-20 11:32:21

+0

這是否將輸出保存到相同的文件名(需要),它也是win32兼容? – user349418 2011-03-20 12:53:41

+0

它將數據打印到STDOUT,您可以使用重定向將其寫入所需位置。您還可以通過添加另一個調用來打開/關閉輸出文件句柄來將內容寫入文件,可能會轉到'$ inputfilename.out'。不過,我強烈建議不要打破源文件。如果你想在那裏放置一些重命名邏輯,Perl也會內置'rename'。 – Lumi 2011-03-20 13:31:12