user934718
user934718

Reputation: 55

join lines after colon (perl)

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 only a word followed by colon with lines that do not contain colon:

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

Upvotes: 0

Views: 519

Answers (3)

flesk
flesk

Reputation: 7589

This also works if the input is provided in a file as an argument to the script, and is a little shorter:

$/=$.;$_=<>;s/\s?\n/, /g;s/, (\w+:),?/\n$1/g;s/, $/\n/;print

It's not very readable, but it works with strict and warnings.

Output:

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

It can probably be shortened even further. -ape or #!perl -ap would be a good start.

Upvotes: 1

Dragon8
Dragon8

Reputation: 1805

This should do the same as RCs code, but a little bit shorter:

my @lines;
while(<FILE>) {
    chomp;
    if(m/^\w+:\s(\w+(,\s)?)*$/) {
            push @lines, $_;
    } else {
            $lines[$#lines] .= ", " unless($lines[$#lines] =~ m/^\w+:\s?$/);
            $lines[$#lines] .= $_;
    }
}
print join "\n", @lines;

Upvotes: 1

user180100
user180100

Reputation:

Here's a quick and dirty version:

#!/usr/bin/perl

use strict;
use warnings;

my $prevLine = "";
my @others;

for(<DATA>) {
    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

Upvotes: 1

Related Questions