Help: Delete a single carriage return in a file, but not a double carriage return?

S

Steve Anderson

I'd like to use perl to remove all single carriage returns, but leave all
double carriage returns intact in a text file.

For example, the following:

foo bar baz
baz bar foo baz
baz

baz foo bar
baz

should become:

foo bar baz baz bar foo baz baz

baz foo bar baz

It sounds simple, but I haven't been able to figure out how to do this.
Can anyone give me a hand?

Thanks,

Steve
 
B

Ben Morrow

Quoth Steve Anderson said:
I'd like to use perl to remove all single carriage returns, but leave all
double carriage returns intact in a text file.

For example, the following:

foo bar baz
baz bar foo baz
baz

baz foo bar
baz

should become:

foo bar baz baz bar foo baz baz

baz foo bar baz

It sounds simple, but I haven't been able to figure out how to do this.
Can anyone give me a hand?

#!/usr/bin/perl

$/ = $\ = "\n\n";

while (<>) {
chomp;
s/\n//g;
print;
}

__END__

Ben
 
A

Anno Siegel

Steve Anderson said:
I'd like to use perl to remove all single carriage returns, but leave all ^^^^^^
double carriage returns intact in a text file.

For example, the following:

foo bar baz
baz bar foo baz
baz

baz foo bar
baz

should become:

foo bar baz baz bar foo baz baz

baz foo bar baz

It sounds simple, but I haven't been able to figure out how to do this.
Can anyone give me a hand?

You say "remove", but from your example you want to replace isolated
line feeds with blanks.

You can use lookbehind and lookahead to make sure a line feed is neither
preceded nor followed by another:

s/(?<!\n)\n(?!\n)/ /g;

Anno
 
S

Steve Anderson

You say "remove", but from your example you want to replace isolated
line feeds with blanks.

You're absolutely right, my text was wrong, my example was right. Thanks
for seeing through it, and thanks for the solution.

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top