You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell替换文件内容时保留换行格式问题求助

解决PowerShell替换文本时保留换行的问题

我来帮你搞定这个换行丢失的问题!核心原因是你读取file1.txt的方式不对,导致原文件的换行符被丢掉了,咱们一步步来修正:

问题根源

当你直接用Get-Content "C:\location\file1.txt"时,PowerShell默认会把文件内容拆成字符串数组(每一行对应数组的一个元素)。当你把这个数组直接放到替换字符串里("$filecontentrn"),PowerShell会自动把数组元素用空格拼接起来,原文件的换行自然就没了——你加的rn只是在拼接后的内容末尾加了个换行,根本没保留原文件的换行结构。

两种解决方案

方案1:用-Raw参数读取完整带换行的内容

最简便的方法是读取file1.txt时也加上-Raw参数,这样会把整个文件内容作为单个包含换行符的字符串读取,替换后自然保留换行:

$filecontent = Get-Content "C:\location\file1.txt" -Raw
(Get-Content -path C:\Location\sample.txt -Raw) -replace "File1Content", $filecontent | Set-Content C:\Export\output.txt

方案2:手动拼接数组为带换行的字符串

如果你的PowerShell版本不支持-Raw(比如PowerShell 2.0及更早),可以用[string]::Join()把数组元素用换行符连接起来:

$filecontent = Get-Content "C:\location\file1.txt"
# 用Windows风格换行符连接数组元素,若为Unix格式文件可换成"`n"
$formattedContent = [string]::Join("`r`n", $filecontent)
(Get-Content -path C:\Location\sample.txt -Raw) -replace "File1Content", $formattedContent | Set-Content C:\Export\output.txt

验证结果

运行上述代码后,output.txt的内容就会变成你期望的格式:

Some pre content goes here
Abcd Efgh HIJK

内容的提问来源于stack exchange,提问作者MysticRose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:18:12