gpt4 book ai didi

Powershell 用一个替换两个空行

转载 作者:行者123 更新时间:2023-12-03 00:28:46 27 4
gpt4 key购买 nike

我有生成的文本文件,每个文本 block 之间有 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

最佳答案

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

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

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

Replace("`r`n`r`n", "`r`n")

总结一下:

(Get-Content -Raw .\test.txt).Replace("`r`n`r`n", "`r`n") | Set-Content .\test.txt

会做的。

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

$data = Get-Content .\test.txt
$data | Where-Object { $_ } | Set-Content .\test.txt

关于Powershell 用一个替换两个空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38023356/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com