如何按字符串中的数字对字符串列表进行排序? [英] How can I sort a list of strings by numbers in them?
问题描述
毫无疑问,这对您来说很简单...
An easy one no doubt for you...
我有一个像这样的文件名列表;
I have a list of filenames which are like so;
fw_d.log.1.gz
through
fw_d.log.300.gz
当我在下面的代码块中使用该代码块时,它几乎按照我想要的方式对其进行了排序,但并不完全.
When i use this below code block, it almost sorts it the way i want, but not quite.
#!/usr/bin/perl -w
my $basedir = "/var/log";
my @verdir = qw(fw_d);
my $fulldir;
my $configs;
my $combidir;
foreach $combidir (@verdir) {
$fulldir = "$basedir/$combidir";
opendir (DIR, $fulldir);
my @files = grep { $_ ne '.' && $_ ne '..' && $_ ne 'CVS' readdir DIR;
closedir (DIR);
@files1 = sort {$a cmp $b}(@files);
foreach my $configs (@files1) {
print "Checking $configs\n";
system("less $basedir/$combidir/$configs | grep \'.* Group = , Username = .* autheauthenticated.\' >> output.log" );
}
}
这是代码段输出
Checking fw_d.log
Checking fw_d.log.1.gz
Checking fw_d.log.10.gz
Checking fw_d.log.100.gz
Checking fw_d.log.101.gz
Checking fw_d.log.102.gz
如您所见,它几乎按照我的希望进行排序....有人对我可以使用的阅读内容或代码段有任何建议吗?
As you can see, it almost sorts it how i was hoping.... Does anyone have any suggestions, on either reading, or a code snippet i can use?
预先感谢.
史蒂夫.
Thanks in advance.
Steve.
推荐答案
您可以使用 Schartzian变换:
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, $_=~/(\d+)/] }
@files;
print Dumper \@sorted;
添加了用于比较Schwartzian-Transform和子例程的基准
Added benchmark for comparison between Schwartzian-Transform and subroutine
use Benchmark qw(:all);
# build list of files
my @files = map {'fw_d.log.'.int(rand()*1000).'.log' } 0 ..300;
my $count = -3;
my $r = cmpthese($count, {
'subname' => sub {
sub expand {
my $file=shift;
$file=~s{(\d+)}{sprintf "%04d", $1}eg;
return $file;
}
my @sorted = sort { expand($a) cmp expand($b) } @files;
},
'schwartzian' => sub {
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, $_=~/(\d+)/] }
@files;
}
});
结果:
Rate subname schwartzian
subname 21.2/s -- -92%
schwartzian 279/s 1215% --
Schwartzian转换对300个文件进行排序的效率提高了约13倍.
Schwartzian-transform is about 13 times more efficient for sorting 300 files.
这篇关于如何按字符串中的数字对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!