user13107
user13107

Reputation: 3489

Per replace newlines not working as expected

I'm trying to replace newlines in a file tmp using Perl, but getting unexpected behavior as shown below.

user$ cat tmp
aa
bb
cc


user$ perl -p -e 's/\n/==/g' tmp
aa==bb==cc==

user$ perl -p -e 's/\nbb/==/g' tmp
aa
bb
cc

Why is the output not

aa==
cc

instead?

Upvotes: 0

Views: 57

Answers (1)

Alexandr Evstigneev
Alexandr Evstigneev

Reputation: 723

The problem here that -p flag loops your code like:

LINE:
    while (<>) {
    ...     # your program goes here
    } continue {
    print or die "-p destination: $!\n";
    }

So your regexp runs for each line. Just use -0777 option to read the entire file as one line:

perl -p -0777 -e 's/\nbb/==/g' tmp

Upvotes: 6

Related Questions