2012-06-15 66 views
0

我有一個包含多個文件的目錄。這些文件命名如下A11111,A22222,A33333,B11111,B22222,B33333等。我想讀取這些文件,對內容執行某些格式化選項並將其寫入輸出文件。但是對於以A開頭的所有文件,我只需要一個輸出文件,對於以B開頭的所有文件,我需要一個輸出文件等等。是否有可能用perl腳本來做到這一點?使用perl腳本從目錄中讀取文件

+6

這是可能的。 [你有什麼試過?](http://whathaveyoutried.com)[顯示你的進度和代碼。](http://stackoverflow.com/questions/how-to-ask)解釋你在沒有其他。 – daxim

+1

你問這是否可能,或者是否有人會提供代碼來完成它?這當然是可能的 – mathematician1975

+1

任何事情都可能與Perl! – Jean

回答

1

下面的例子應該是你一個良好的開端:

#!/usr/bin/perl 

use strict; 
use warnings; 

my $dir = '.'; 

opendir my $dh, $dir or die "Cannot open $dir: $!"; 
my @files = sort grep { ! -d } readdir $dh; 
closedir $dh; 

$dir =~ s/\/$//; 

foreach my $file (@files) { 
    next if $file !~ /^[A-Z](\d)\1{4}$/; 

    my $output = substr($file, 0, 1); 
    open(my $ih, '<', "$dir/$file") or die "Could not open file '$file' $!"; 
    open(my $oh, '>>', "$dir/$output") or die "Could not open file '$output' $!"; 

    $_ = <$ih>; 
    # perform certain formating with $_ here 
    print $oh $_; 

    close($ih); 
    close($oh); 
} 

在行next if $file !~ /^[A-Z](\d)\1{4}$/;它跳過不在所需的格式,它是第一個字符是大寫字母所有文件名,第二個是數字另外4個字符與第一個數字相同。

0

如果您在Linux上使用'貓文件1文件2 ...>工作大文件

否則這裏是一個小的腳本來幫助你在路上

use strict; 
use warnings; 

# get the directory from the commandline 
# and clean ending/
my $dirname = $ARGV[0]; 
$dirname =~ s/\/$//; 

# get a list of all files in directory; ignore all files beginning with a . 
opendir(my $dh, $dirname) || die "can't opendir $dirname: $!"; 
my @files = grep { /^[^\.]/ && -f "$dirname/$_" } readdir($dh); 
closedir $dh; 

# loop through the files and write all beginning with 
# A to file A, B to file B, etc. extent the regex to fit your needs 
foreach my $file (@files) { 
    if ($file =~ /([AB])\d+/) { 
     open(IN, "< $dirname/$file") or die "cant open $dirname/$file for reading"; 
     open(OUT, ">> $dirname/$1") or die "cant open $dirname/$1 for appending"; 
     print OUT <IN>; 
     close(OUT); 
     close(IN); 
    } else { 
     print "$file didn't match\n"; 
    } 
}