2012-06-15 47 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"; 
    } 
}