我有一些数据集(foo),以bar和baz作为部分的输出。应该将带有baz的部分排序为输出的顶部。
示例输入;
= foo4 =
bar
(..)
barN
= foo1 =
bar
(..)
barN
= foo5 =
bar
(..)
barN
baz
= foo2 =
bar
(..)
barN
= foo3 =
bar
(..)
barN
baz在上面的示例中,我希望将节= foo3 =和= foo5 =移到输出的顶部,并按“名称”部分对列表进行子排序。
= foo3 =
= foo5 =
= foo1 =
= foo2 =
= foo4 =但这部分的内容完好无损。
发布于 2013-07-29 12:24:30
Perl解决方案它使用节的散列,键是节的名称,值包含节开始所在的文件中的位置以及是否存在baz的信息。一旦文件被读入哈希,键就会被排序,内容就会被打印出来,就像记忆中的那样在文件周围移动。
#!/usr/bin/perl
use warnings;
use strict;
my $file = shift;
my $start = qr/^= (.*) =$/;
open my $FH, '<', $file or die $!;
my %sections;
my $current_section;
while (<$FH>) {
if (/$start/) {
$current_section = $1;
$sections{$current_section}{begin} = tell $FH;
} elsif (/baz/) {
$sections{$current_section}{baz} = 1;
}
}
for my $section (map substr( $_, 1),
sort map { ($sections{$_}{baz} ? '0' : '1') . $_ }
keys %sections) {
seek $FH, $sections{$section}{begin}, 0;
print "= $section =\n";
while (<$FH>) {
last if /$start/;
print;
}
}发布于 2013-07-29 23:48:21
洛塔斯塔夫溶液,a.,脂肪
awk '/^=/{print ""} {printf "%s\t", $0}' input.txt | \
awk '{print ($NF != "baz")"\t"$0}' | sort -n | cut -f 2- | \
tr '\t' '\n' | sed -e '/^$/d'最初的转变太挑剔了。应该有一些工具可以粘贴线条,直到分隔符(:
https://stackoverflow.com/questions/17923470
复制相似问题