我想用下面的Schwartzian轉換排序腳本(這是工作完全作爲一個獨立的腳本),在多個文件夾中的變換:使用的Schwartzian在多個文件
#!/usr/bin/perl
use strict;
use warnings;
open my $input, '<', '/home/test/file1' or die "Unable to open input file: $!";
my @file = <$input>;
my @sorted_file = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { my ($x) = $_ =~ /VerNumber:\((\d+)/i; [$_, $x]; }
@file;
open my $output, '>', '/home/test/sorted/file1' or die "Unable to open output file: $!";
print $output $_ for @sorted_file;
腳本應該採取作爲輸入一個文件夾中的所有文件開頭的文件*,而且每一個的內容進行排序:
file1.txt
file2.txt
...
file1000.txt
那麼,作爲一個輸出,我想爲腳本創建新文件夾,在其中將放置新文件與排序後的內容保持相同的文件名秒。
/sorted
file1.txt -> /sorted/file1.txt
file2.txt -> /sorted/file2.txt
...
file1000.txt -> /sorted/file1000.txt
任何想法如何有效地做到這一點?我有近1000個文件,每個文件包含大約3000個數組,這些文件正在使用上述腳本進行排序。
我做了一個嘗試。以下腳本將輸出文件夾中的文件寫入,保留相同的文件名,但排序部分不起作用(即使獨立腳本正在排序文件)。我在輸出中獲得相同的文件。
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
my $version="0.2";
my $files_match="";
my $files_dir="";
my $file_name="";
my $help_flag="";
my $version_flag="";
GetOptions(
'm|match=s' => \$files_match,
'd|directory=s' => \$files_dir,
'h|help' => \$help_flag, 'v|version' => \$version_flag,
);
sub sorting {
my @file = "$_";
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { my ($x) = $_ =~ /VerNumber:\((\d+)/i; [$_, $x]; }
@file;
print FILE $_;
}
if (($files_match ne "") and ($files_dir ne "")) {
chdir("$files_dir") or die "$!";
opendir (DIR, ".") or die "$!";
my @files = grep {/$files_match/} readdir DIR;
my $files_size = $#files + 1;
my $index_file = 1;
print "Files to process: $files_size\n";
close DIR;
foreach (@files) {
open(FILE, ">./sorted/$_.sort") or die $!;
my @singlefile = $_;
print "Processing $index_file of $files_size files: $_\n";
local @ARGV = @singlefile;
while(<>){
sorting($_);
}
close(FILE);
$index_file++;
print "OK: Sorted @singlefile \n";
}
} elsif ((!$help_flag) and (!$version_flag)){printHelp();}
我是一個Perl的初學者,任何幫助都會比歡迎!
預先感謝您!
如果您已經嘗試編寫解決方案但無法使其工作,我們將很樂意幫助您。如果你不嘗試某些東西*,你將永遠留在初學者。 – Borodin
Your line'打開我的$輸出,'>'或死「無法打開輸出文件:$!」'是錯誤的。你還沒有提供文件名。 – Borodin
「open my $ input」,「<」或「...」 - 缺少文件名。使用核心模塊['File :: Path'](http://perldoc.perl.org/File/Path.html)中的'make_path'創建一個目錄。獲取要處理的文件列表,例如['glob'](http://perldoc.perl.org/functions/glob.html)。然後遍歷這個列表,主要是你在做什麼。讓我們知道是否有問題。 – zdim