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

PowerShell如何实现在TXT文件每两行后插入换行符

PowerShell 按两行分组插入空行输出实现方案

直接处理数组场景

假设你待输出的数组为$arr,可通过遍历计数的方式实现分组分隔,示例代码如下:

# 示例数组,可替换为你自己的数组变量
$arr = @("Value11", "Value12", "Value21", "Value22")

$arr | ForEach-Object -Begin { $lineCount = 0 } -Process {
    # 输出当前行内容
    $_
    $lineCount++
    # 每满2行插入空行
    if ($lineCount % 2 -eq 0) {
        ""
    }
} | Out-File -FilePath "输出文件路径.txt" -Encoding UTF8

避免末尾多余空行优化版

上述代码会在最后一组内容后也输出空行,如果你不需要末尾的多余空行,可增加末尾判断逻辑:

$arr | ForEach-Object -Begin { $lineCount = 0; $totalLines = $arr.Count } -Process {
    $_
    $lineCount++
    if ($lineCount % 2 -eq 0 -and $lineCount -ne $totalLines) {
        ""
    }
} | Out-File -FilePath "输出文件路径.txt" -Encoding UTF8

已有TXT文件批量处理场景

如果你已经生成了无空行的连续内容TXT文件,可直接读取文件内容处理后重新输出:

Get-Content -Path "原文件路径.txt" | ForEach-Object -Begin { $lineCount = 0 } -Process {
    $_
    $lineCount++
    if ($lineCount % 2 -eq 0) {
        ""
    }
} | Out-File -FilePath "处理后文件路径.txt" -Encoding UTF8

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:45:02