Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace newlines, but keep the blank lines

I want to replace newlines (\r\n) with space, but I want to keep the blank lines. In other words, I want to replace \r\n with ' ', if \r\n is not preceded by another \r\n. For example:

line 1

line 2
line 3
line 4

Shold end up as...

line 1

line 2 line 3 line 4

But not as "line 1 line 2 line 3 line 4", which is what I'm doing right now with this

preg_replace("/\r\n/", " ", $string);
like image 709
ssam Avatar asked Mar 10 '11 10:03

ssam


People also ask

How do you replace a blank line?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text.

Which command is used to squeeze multiple blank lines to one blank line?

If you aren't firing vim or sed for some other use, cat actually has an easy builtin way to collapse multiple blank lines, just use cat -s .

How to remove extra whitespace by regex?

To remove extra whitespace (i.e. more than one consecutive spaces), use the same regex \s+ but replace the found matches with a single space character.

How do you delete multiple new line characters in Python?

Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.


1 Answers

Try this:

(?<!\n)\n(?!\n)

Of course, you can change \n to whatever you need.

Working example: http://ideone.com/dF5L9

like image 189
Kobi Avatar answered Oct 07 '22 08:10

Kobi