我是PowerShell的新手。我有一个简单的PowerShell脚本,它只替换文本,但我发现生成输出时,regex replace将我的多行数据源转换为单行文本。我要保留换行符。这是这个脚本的愚蠢版本。
$source=(Get-Content textfile.txt) $process1 = [regex]::Replace($source, "line", "line2") $process1 | out-file -encoding ascii textfile2.txt
您可以创建一个名为textfile.txt的测试文件,使用类似这样的简单行来测试它。
line line Some line More line here
我错过了一些明显的东西吗?
谢谢, 法德里安
你的问题是 Get-Content 返回A string[] (源文件中每行一个项目)同时 [regex]::Replace 需要一个字符串。这就是为什么数组首先被转换成一个字符串,这就意味着将所有项集中在一起。
Get-Content
string[]
[regex]::Replace
PowerShell提供 -replace 将更优雅地处理此情况的操作员:
-replace
(Get-Content .\textfile.txt) -replace 'line', 'line2' | out-file -encoding ascii textfile2.txt
这个 -替换 运算符对数组中的每个项分别进行操作,并将其应用于数组。
-替换
是的,它执行正则表达式匹配和替换。例如:
> (Get-Content .\textfile.txt) -replace '(i|o|u)', '$1$1' liinee liinee Soomee liinee Mooree liinee heeree
多读一点 here 和 here .