[powershell] How can I replace newlines using PowerShell?

Given test.txt containing:

test
message

I want to end up with:

testing
a message

I think the following should work, but it doesn't:

Get-Content test.txt |% {$_-replace "t`r`n", "ting`r`na "}

How can I do a find and replace where what I'm finding contains CRLF?

This question is related to powershell

The answer is


You can use "\\r\\n" also for the new line in powershell. I have used this in servicenow tool.

In my case "\r\n" s not working so i tried "\\r\\n" as "\" this symbol work as escape character in powershell.


In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)


With -Raw you should get what you expect


In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)


With -Raw you should get what you expect


If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.

(Get-Content test.txt) -join ","

This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.


If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.

(Get-Content test.txt) -join ","

This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.