替换换行符时出现问题
我试图用 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
但我没有成功,有人能告诉我,错误在哪里吗?
Iam trying to replace following string with PowerShell:
...
("
Intel(R) Network Connections 14.2.100.0
","
14.2.100.0
")
...
The code that I use is:
Get-Content $logfilepath |
Foreach-Object { $_ -replace '`r`n`r`n', 'xx'} |
Set-Content $logfilepath_new
But I have no success, can someone say me, where the error is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您在替换字符串中使用单引号 -
这意味着它们被逐字处理而不是换行符,因此您必须使用 -
要替换,将文件作为字符串读取并使用
Replace()
方法First, you are using single quotes in the replace string -
that means they are treated verbatim and not as newline characters, so you have to use -
To replace, read the file as string and use the
Replace()
methodGet-content 返回一个行数组,因此 CRLF 本质上是您的分隔符。两个背对背的 CRLF 序列将被解释为当前行的末尾,后跟一个空行,因此任何行(对象)都不应包含 '`r`n`r`n'。多行正则表达式替换可能是更好的选择。
Get-content returns an array of lines, so CRLF is essentially your delimiter. Two CRLF sequences back to back would be interpreted as the end of the currrent line, followed by a null line, so no line (object) should contain '`r`n`r`n'. A multi-line regex replace would probably be a better choice.
作为使用 PS cmdlet 的替代方法:
as alternate method using PS cmdlets:
我使用以下代码将
somestring
替换为换行符:I used the following code to replace
somestring
with newline: