Patrik Patrik - 6 months ago 12
Perl Question

Combine continuation lines starting with "+"

I know this is a question that was asked many times, I didn't find an answer that answers my specific question.

Essentially, I have an input file where some lines begin with a

+
string. These lines must be appended at the end of the previous line and the
+
character must be removed. So

abc
def
+ ghj
klm


should become

abc
def ghj
klm


This is the perl command I crafted by looking at other answers

perl -pe 's/\n\+ //m' < input


but it prints the input file without changing it. The odd thing is that, on websites like regex101.com, my regex produces the expected result.

What am I missing?

Answer

Presumably these are relatively small files and so will easily fit into memory?

This is the simplest way

use strict;
use warnings qw/ all FATAL /;

my $data = do {
    local $/;
    <DATA>;
};

$data =~ s/\n\+//g;

print $data;

__DATA__
abc
def
+ ghj
klm

output

abc
def ghj
klm

In a Perl one-liner that would be

perl -0777 -pe 's/\n\+//g' < input