Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

regex - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 .extfile.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 .extfile.txt) -replace '(i|o|u)', '$1$1'
liinee
liinee
Soomee liinee
Mooree liinee heeree

Read a bit more here and here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...