Perl 对文件的子节进行排序
我需要比我更有经验的人提供一些Perl智慧 到目前为止,我对以下内容的回答是,只需逐行遍历文件,将相关元素插入数组,对数组进行排序,然后附加内容。但这似乎有点冗长,效率不高 我有一个文件,其内容如下:Perl 对文件的子节进行排序,perl,sorting,Perl,Sorting,我需要比我更有经验的人提供一些Perl智慧 到目前为止,我对以下内容的回答是,只需逐行遍历文件,将相关元素插入数组,对数组进行排序,然后附加内容。但这似乎有点冗长,效率不高 我有一个文件,其内容如下: # A Comment # Another comment :127.100.100.255:Something .789 .123 .456 :127.200.200.100:Something Else .bravo.example.com # <---- noperiod.exam
# A Comment
# Another comment
:127.100.100.255:Something
.789
.123
.456
:127.200.200.100:Something Else
.bravo.example.com # <----
noperiod.example.com # <---- This list is
.an.example.com # <---- not ordered
.some.example.com # <----
在Perl中有没有一种聪明的方法,理想情况下是使用一行程序对第二个列表进行排序?i、 e.因此,您将得到以下结果:
# A Comment
# Another comment
:127.100.100.255:Something
.789
.123
.456
:127.200.200.100:Something Else
.an.example.com # <----
.bravo.example.com # <---- NOW this list
noperiod.example.com # <---- IS ordered ;-)
.some.example.com # <----
需要注意的四件事:
要排序的内容始终位于文件的底部
标题:127.200.200.100等始终相同
名称可能以句点开头,也可能不以句点开头,例如..bravo.example.com vs.noperiod.example.com
可能有大量项目,因此需要合理有效
这取决于你所说的“高效”是什么意思。我的意思是,一行程序很少有效率,而且它也很少简洁或清楚地说明它在做什么 但是在效率方面呢?嗯,这取决于你已经在做什么,这是低效的。我的意思是,从根本上说,如果你要对一些东西进行排序,你需要检查整个数据集。否则,您如何知道文件中的最后一行需要排序到顶部 但对于你所做的,我会这样处理:
#!/usr/bin/perl
use strict;
use warnings;
sub sort_noperiods {
my $a_np = $a;
$a_np =~ s/\.//g;
my $b_np = $b;
$b_np =~ s/\.//g;
return $a_np cmp $b_np;
}
while ( <> ) {
print;
last if m/Something Else/;
}
print sort sort_noperiods <>;
对于您的示例输入,打印:
# A Comment
# Another comment
:127.100.100.255:Something
.789
.123
.456
:127.200.200.100:Something Else
.an.example.com # <---- not ordered
.bravo.example.com # <----
noperiod.example.com # <---- This list is
.some.example.com # <----
我正在键入文件中的“其他内容”行,因为我不太清楚如何识别“头”块的最后一行。其他任何内容都会被读入并根据“noperiods”排序机制进行排序。缓存正则表达式的结果可能会有一点效率提高,但我不确定这一点
这可以通过以下方式“一行化”:
perl -e 'while ( <> ) { print; last if m/Something Else/ }; print sort { $a =~ s/\.//gr cmp $b =~ s/\.//gr } <>; '
您可以在Perl的帮助下按shell对其进行排序:只需在列表前的每一行前面加上行号,对于列表,使用其第一行的编号。然后按数字进行数字排序,然后按行的其余部分进行第二次排序:
perl -ne 'if (1 .. /^:127\.200\.200\.100:.*/) {
print "$.\t$_";
} else {
print $.--, "\t$_"
}' file.txt \
| sort -k1,1n -k2 | cut -f2-
句号“算数”吗?例如,“b”为“b”,但“noperiod”为“n”?和基本上不,在不读取整个数据集的情况下,您无法对数据集进行排序-否则,您如何知道是否需要首先输出最后一行?不,周期不计入排序。。。例如。