mmccoo
mmccoo

Reputation: 8536

How can I remove linebreaks with a Perl regex?

when I run:

perl -e '$x="abc\nxyz\n123"; $x =~ s/\n.*/... multiline.../; printf("str %s\n", $x);'

I expect result to be:

str abc... multiline...

instead I get

str abc... multiline...
123

Where am I going wrong?

Upvotes: 3

Views: 8732

Answers (2)

chaos
chaos

Reputation: 124297

$x =~ s/\n.*/... multiline.../s

/s modifier tells Perl to treat the matched string as single-line, which causes . to match newlines. Ordinarily it doesn't, resulting in your observed behavior.

Upvotes: 7

EvanK
EvanK

Reputation: 1072

You need to use the 's' modifier on your regex, so that the dot '.' will match any subsequent newlines. So this:

$x =~ s/\n.*/... multiline.../;

Becomes this:

$x =~ s/\n.*/... multiline.../s;

Upvotes: 2

Related Questions