Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell replace lose line breaks

I am a newbie in powershell. I have a simple powershell script that just replace text but I found that the regex replace turn my multiline data source into a single line text when the output is produced. I want the line breaks to be preserved. Here is the dumb down version of the script.

$source=(Get-Content textfile.txt)

$process1 = [regex]::Replace($source, "line", "line2")

$process1 | out-file -encoding ascii textfile2.txt

You can create a test file call textfile.txt with simple lines like this to test it

line 
line
Some line
More line here

Have I missed something obvious?

Thanks, Fadrian

like image 922
Fadrian Sudaman Avatar asked Apr 28 '10 03:04

Fadrian Sudaman


People also ask

How do I remove a line break in PowerShell?

Replace("'r'n",", ")) (replace ' with backtick) ? If the Replace method doesn't work, try $($message. Body -join ", ") instead. That's the way to do it if it's actually a string-array string[] .

How do I replace a space in a new line in PowerShell?

Use the PowerShell String replace() method or replace operator to replace the space in a string with a new line. e.g. $str. replace(" ","`r`n") replace the space with a new line.

How do I change special characters in PowerShell?

PowerShell replace operator uses regular expression (regex) to search characters or strings, hence to replace a special character, use escape character '\' before the special character.

How do you break a line in PowerShell?

Use `N to Break Lines in PowerShell You can use the new line `n character to break lines in PowerShell. The line break or new line is added after the `n character.


1 Answers

Your problem here is that Get-Content returns a string[] (with one item for each line in the source file) while [regex]::Replace expects a string. That's why the array will first be converted to a string which simply means lumping together all items.

PowerShell provides a -replace operator which will handle this case more gracefully:

(Get-Content .\textfile.txt) -replace 'line', 'line2' | 
   out-file -encoding ascii textfile2.txt

The -replace operator operates on each item of an array individually i it's applied to an array.

And yes, it does regular expression matches and replaces. For example:

> (Get-Content .\textfile.txt) -replace '(i|o|u)', '$1$1'
liinee
liinee
Soomee liinee
Mooree liinee heeree

Read a bit more here and here.

like image 121
James Kolpack Avatar answered Oct 15 '22 23:10

James Kolpack