Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace newlines using PowerShell?

Tags:

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?

like image 901
Iain Avatar asked Nov 28 '08 14:11

Iain


People also ask

How do I replace a value in PowerShell?

Using the Replace() Method The replace() method has two arguments; the string to find and the string to replace the found text with. As you can see below, PowerShell is finding the string hello and replacing that string with the string hi . The method then returns the final result which is hi, world .

How do you replace multiple lines in PowerShell?

Try the following: Convert the existing profile contents to a multiline string - by default Get-Content returns an array of strings, just pipe it to Out-String. You'll need a regex "mode-modifier" to ensure the statement searches multiple lines and the wildcard includes line breaks - see here for an explanation.


2 Answers

A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

PS C:\> $x = "Hello >> World"  PS C:\> $x Hello World PS C:\> $x.contains("`n") True PS C:\> $x.contains("`r") False PS C:\> $x.replace("o`nW","o There`nThe W") Hello There The World PS C:\> 

I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

like image 58
Don Jones Avatar answered Nov 02 '22 19:11

Don Jones


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 :)

like image 32
Peter Seale Avatar answered Nov 02 '22 20:11

Peter Seale