如何按字符串中的数字对字符串列表进行排序?
我有一个文件名列表,如下所示:
fw_d.log.1.gz
through
fw_d.log.300.gz
当我使用下面的代码块时,它几乎按照我想要的方式对其进行排序,但不完全是:
#!/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
正如您所看到的,它几乎按照我想要的方式对其进行排序希望...有人对阅读或我可以使用的代码片段有任何建议吗?
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 code block below, 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" );
}
}
Here is a snippet output:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Schartzian-transform :
添加了 Schwartzian-Transform 和子例程之间比较的基准
结果:
对于 300 个文件进行排序,Schwartzian 变换的效率大约提高了 13 倍。
You could use Schartzian-transform :
Added benchmark for comparison between Schwartzian-Transform and subroutine
Result:
Schwartzian-transform is about 13 times more efficient for sorting 300 files.
问题是代码执行了您告诉它执行的操作:按字母顺序对文件名进行排序。
您应该将
sort { $a cmp $b }
替换为sort { Expand($a) cmp Expand($b) }
和
expand
:the problem is that the code does what you tell it to do: sort the file names in alphabetical order.
You should replace
sort { $a cmp $b }
bysort { expand($a) cmp expand($b) }
with
expand
:您可以尝试使用自定义排序函数:
然后像这样排序:
这将按每个字符串中第一个数字的值对
@files
中的字符串进行排序。What you can try is using a custom sort function:
and then sort like this:
This will sort the strings in
@files
by the value of the first number in each string.较旧的问题,但尚未提及答案。
排序::自然
为您执行此操作:此顺序为:
Older question, but there's an answer as yet unmentioned.
Sort::Naturally
does this for you:This orders as: