gpt4 book ai didi

regex - 在perl中对文本 block 进行排序

转载 作者:行者123 更新时间:2023-12-02 06:39:22 24 4
gpt4 key购买 nike

我有一个看起来像这样的文件:

SECTION1 id name  
sub section1
sub section2
SECTION2 id name
sub section3
sub section4
sub section6
SECTION1 id name
sub section7
sub section8
SECTION3 id name
sub section9
sub section10
sub section11
sub section12
SECTION2 id name
sub section13
sub section14
SECTION1 id name
sub section15
sub section16
SECTION3 id name
sub section17
sub section18

我需要按部分对这个文件进行排序。我唯一知道的是我有“SECTION1”、“SECTION2”和“SECTION3”。排序后的预期输出是:

SECTION1 id name  
sub section1
sub section2
SECTION1 id name
sub section7
sub section8
SECTION1 id name
sub section15
sub section16
SECTION2 id name
sub section3
sub section4
sub section6
SECTION2 id name
sub section13
sub section14
SECTION3 id name
sub section9
sub section10
sub section11
sub section12
SECTION3 id name
sub section17
sub section18

在 perl 中或使用 grep、sed 等实用程序是否有任何简单的方法可以做到这一点?

最佳答案

另一种使用 perl 的方法:

假设 infile 包含问题的内容和以下 script.pl 的内容:

use warnings;
use strict;
use sort qw/stable/;

my ($section, @section);

while ( <> ) {

## Save text if first line or when line doesn't begin with 'SECTION' word.
if ( $. == 1 || $_ !~ m/\ASECTION\d+/ ) {
$section .= $_;
next unless eof;
}

## Save the text and the number of section.
if ( $section =~ m/\ASECTION(\d+)/ ) {
push @section, [ $1, $section ];
$section = q||;
}

## Begin to save next section.
$section .= $_;
}

## Print them sorted by section number.
for ( sort { $a->[0] <=> $b->[0] } @section ) {
printf qq|%s|, $_->[1];
}

像这样运行它:

perl script.pl infile

输出如下:

SECTION1 id name  
sub section1
sub section2
SECTION1 id name
sub section7
sub section8
SECTION1 id name
sub section15
sub section16
SECTION2 id name
sub section3
sub section4
sub section6
SECTION2 id name
sub section13
sub section14
SECTION3 id name
sub section9
sub section10
sub section11
sub section12
SECTION3 id name
sub section17
sub section18

关于regex - 在perl中对文本 block 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com