2012-06-15 2 views
0

여러 파일이있는 디렉토리가 있습니다. 파일의 이름은 A11111, A22222, A33333, B11111, B22222, B33333 등과 같습니다. 이 파일들을 읽고, 컨텐트에 대한 특정 포맷 옵션을 수행하여 출력 파일에 쓰고 싶습니다. 그러나 A로 시작하는 모든 파일에 대해 하나의 출력 파일 만 필요합니다. B로 시작하는 모든 파일에 대해 하나의 출력 파일이 필요합니다. 펄 스크립트로 이것을 할 수 있습니까?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

당신이 그렇지 않으면 여기

TEST_TBS는 빅 리눅스 사용`고양이 파일 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"; 
    } 
}