【问题标题】:Powershell Replace two empty lines with onePowershell 用一个替换两个空行
【发布时间】:2016-10-27 15:52:03
【问题描述】:

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

【问题讨论】:

  • Test.txt 的内容是什么你也许可以使用Trim() 方法删除空格。
  • 使用`代替\来转义控制字符
  • @Ramil 如果您发现任何答案有帮助,请接受。
  • 抱歉,忘记添加内容了。我目前正在处理一个看起来像这样的测试文件。 text 下一个文本块(对不起,我不知道如何在 cmets 中添加空行,但你应该明白我的意思:P)

标签: powershell replace


【解决方案1】:

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

【讨论】:

  • 另一种方法是过滤掉空行: - $data -ne ''
  • @iTayb 谢谢,它有效:D 我使用第一个解决方案,因为我不想删除所有空行。所以 Powershell 有时会接受 regex.. 这样的命令 \n,但有时需要反引号版本`n。你能指出一些材料吗?为什么会这样?
【解决方案2】:

PowerShell 使用反引号 ` 而不是反斜杠 \ 来转义特殊字符:

(Get-Content .\test.txt) -replace "(`r?`n){2}",$([Environment]::Newline) | Set-Content .\test.txt

使用带有条件回车符的正则表达式-replace 运算符将匹配任何类型的换行符。

【讨论】:

  • 感谢您指出这一点。昨天当我试图在变量和字符串之间转义 _(下划线)时发现它(例如:Rename-Item -Path $LogPath -NewName "$Today`_logfile.log")。对尚未弄清楚这一点的任何人都有用:)
猜你喜欢
  • 2018-03-20
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
相关资源
最近更新 更多