替换换行符时出现问题

发布于 2024-11-28 04:39:44 字数 306 浏览 1 评论 0原文

我试图用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

亽野灬性zι浪 2024-12-05 04:39:44

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

'`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")

First, you are using single quotes in the replace string -

'`r`n`r`n'

that means they are treated verbatim and not as newline characters, so you have to use -

"`r`n`r`n"

To replace, read the file as string and use the Replace() method

$content=[string] $template= [System.IO.File]::ReadAllText("test.txt")
$content.Replace("`r`n`r`n","xx")
鲜血染红嫁衣 2024-12-05 04:39:44

Get-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.

一个人的旅程 2024-12-05 04:39:44

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

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

as alternate method using PS cmdlets:

Get-Content $logfilepath | 
    Foreach-Object -Begin { $content="" } -Process { $content += $_ ; $content += "xx" } -End { $content } | 
    Set-Content $logfilepath_new
纵山崖 2024-12-05 04:39:44

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

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

I used the following code to replace somestring with newline:

$nl = [System.Environment]::NewLine
$content = $content.Replace( somestring, $nl )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文