Max
Max

Reputation: 157

Deleting line breaks in a text file with a condition

I have a text file. Some of the lines in it end with lf and some end with crlf. I only need to delete lfs and leave all crlfs.

Basically, my file looks like this

Mary had a lf

dog.crlf

She liked her lf

dog very much. crlf

I need it to be

Mary had a dog.crlf

She liked her dog very much.crlf

Now, I tried just deleting all lfs unconditionally, but then I couldn't figure out how to write it back into the text file. If I use File.WriteAllLines and put a string array into it, it automatically creates line breaks all over again. If I use File.WriteAllText, it just forms one single line. So the question is - how do I take a text file like the first and make it look like the second? Thank you very much for your time. BTW, I checked similar questions, but still have trouble figuring it out.

Upvotes: 1

Views: 4221

Answers (3)

Meta-Knight
Meta-Knight

Reputation: 17855

This is an alternative to Brad Christie's answer, which doesn't use Regex.

String result = sampleFileContent.Replace("\r\n", "**newline**")
                                 .Replace("\n","")
                                 .Replace("**newline**","\r\n");

Here's a demo. Seems faster than the regex solution according to this site, but uses a bit more memory.

Upvotes: 2

Sga
Sga

Reputation: 3658

Just tested it:

string file = File.ReadAllText("test.txt");
file = file.Replace("\r", "");
File.WriteAllText("test_replaced.txt", file);

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

Use regex with a negative look-behind and only replace the \n not preceded by a \r:

DEMO

var result = Regex.Replace(sampleFileContent, @"(?<!\r)\n", String.Empty);

The (?<! ... ) is a negative look-behind. It means that we only want to replace instances of \n when there isn't a \r directly behind it.

Disclaimer: This may or may not be as viable an option depending on the size of your file(s). This is a good solution if you're not concerned with overhead or you're doing some quick fixes, but I'd look in to a more robust parser if the files are going to be huge.

Upvotes: 2

Related Questions