Powershell 替换丢失的换行符 [英] Powershell replace lose line breaks
问题描述
我是 powershell 的新手.我有一个简单的 powershell 脚本,它只是替换文本,但我发现正则表达式替换在生成输出时将我的多行数据源转换为单行文本.我希望保留换行符.这是脚本的愚蠢版本.
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
您可以创建一个测试文件调用 textfile.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?
谢谢,法德里安
推荐答案
你的问题是 Get-Content
返回一个 string[]
(源文件中的每一行都有一个项目)而 [regex]::Replace
需要一个字符串.这就是为什么数组首先会被转换为一个字符串,这意味着将所有项目集中在一起.
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 提供了一个 -replace
操作符,可以更优雅地处理这种情况:
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
-replace
运算符单独对数组的每一项进行操作,并将其应用于数组.
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
这篇关于Powershell 替换丢失的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!