join lines after colon (perl)

后端 未结 3 753
忘了有多久
忘了有多久 2021-01-27 23:21

I have this lines:

alpha: beta
beta: alpha, beta
omega: beta, gamma, alpha
gamma: 
alpha
beta
gamma
epsilon: alpha

I want to join line contains

3条回答
  •  不思量自难忘°
    2021-01-28 00:14

    Here's a quick and dirty version:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $prevLine = "";
    my @others;
    
    for() {
        chomp;
        if (/:\s*$/) { # lines ends with : and potential space after
            $prevLine = $_;
        } elsif (!/:/) { # line doesn't contain ':'
            push(@others, $_);
        } elsif ($prevLine eq "") { # this is a "x: y, z" line, nothing in buffer
            print $_ . "\n";
        } else { # this is a "x: y, z" line, with a previous line in buffer
            print $prevLine . join(", ", @others) . "\n" . $_ . "\n";
        }
    }
    
    __DATA__
    alpha: beta
    beta: alpha, beta
    omega: beta, gamma, alpha
    gamma: 
    alpha
    beta
    gamma
    epsilon: alpha
    

    Output:

    alpha: beta
    beta: alpha, beta
    omega: beta, gamma, alpha
    gamma: alpha, beta, gamma
    epsilon: alpha
    

提交回复
热议问题