更换换行的问题

时间:2011-08-03 11:28:06

标签: powershell

我试图用PowerShell替换以下字符串:

...
("
Intel(R) Network Connections 14.2.100.0
","
14.2.100.0
")
...

我使用的代码是:

Get-Content $logfilepath | 
Foreach-Object { $_ -replace '`r`n`r`n', 'xx'} | 
Set-Content $logfilepath_new

但我没有成功,有人能说我,错误在哪里吗?

4 个答案:

答案 0 :(得分:3)

首先,您在替换字符串中使用单引号 -

'`r`n`r`n'

这意味着它们被逐字处理而不是换行符,因此您必须使用 -

"`r`n`r`n"

要替换,请将该文件作为字符串读取并使用Replace()方法

$content=[string] $template= [System.IO.File]::ReadAllText("test.txt")
$content.Replace("`r`n`r`n","xx")

答案 1 :(得分:2)

Get-content返回一个行数组,因此CRLF本质上就是你的分隔符。两个背靠背的CRLF序列将被解释为currrent行的末尾,后面是一个空行,因此没有行(对象)应该包含'r`n`r`n'。多行正则表达式替换可能是更好的选择。

答案 2 :(得分:0)

作为使用PS cmdlet的替代方法:

Get-Content $logfilepath | 
    Foreach-Object -Begin { $content="" } -Process { $content += $_ ; $content += "xx" } -End { $content } | 
    Set-Content $logfilepath_new

答案 3 :(得分:0)

我使用以下代码将somestring替换为换行符:

$nl = [System.Environment]::NewLine
$content = $content.Replace( somestring, $nl )
相关问题