Powershell 将两个空行替换为一个

Ram*_*mil 4 powershell replace

我生成的文本文件在每个文本块之间有 2 个空行。我可以使用 Notepad++ 将 \r\n\r\n 替换为 \r\n 来完成此操作,但必须有一种方法可以自动执行此操作。

我尝试在 Powershell 中想出一些办法,但到目前为止还没有任何效果。

这是我到目前为止所尝试过的:

(Get-Content .\test.txt).Replace("\n\n",'\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\s+\r\n+",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n+",'') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\n+",'') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n\r\n",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\s+\r\n)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\s+\r\n+)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\r\n+)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n",'\b') | Set-Content .\test.txt
Run Code Online (Sandbox Code Playgroud)

iTa*_*ayb 6

Get-Content返回字符串列表,而不是像您需要的那样返回整段文本。显然,您的意思是在字符串上运行此Replace方法,而不是在字符串列表上运行。

用于Get-Content -Raw .\test.txt将文件内容加载为一个长字符串。

此外,替换的正确形式是:

Replace("`r`n`r`n", "`r`n")
Run Code Online (Sandbox Code Playgroud)

总结:

(Get-Content -Raw .\test.txt).Replace("`r`n`r`n", "`r`n") | Set-Content .\test.txt
Run Code Online (Sandbox Code Playgroud)

会做这项工作。

另一种方法是过滤掉空行:

$data = Get-Content .\test.txt
$data | Where-Object { $_ } | Set-Content .\test.txt
Run Code Online (Sandbox Code Playgroud)