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

Windows环境下PowerShell筛选多CSV中RecvByts连续重复行

批量处理CSV文件保留RecvByts连续重复行的PowerShell解决方案

实现思路

遍历目标文件夹下所有CSV文件,逐行读取内容并跟踪上一行的RecvByts值:

  • 若当前行RecvByts与上一行相同,则将两行都加入保留列表
  • 处理完成后将保留的行写入新文件(避免覆盖原文件)

可行代码实现

# 替换为你的CSV文件所在文件夹路径
$targetFolder = "C:\Your\CSV\Directory"
# 获取文件夹内所有CSV文件
$csvFiles = Get-ChildItem -Path $targetFolder -Filter "*.csv"

foreach ($file in $csvFiles) {
    # 读取CSV内容,自动解析为对象
    $originalData = Import-Csv -Path $file.FullName
    $filteredRows = @()
    $previousRecvByts = $null
    $previousRow = $null

    foreach ($currentRow in $originalData) {
        # 第一行仅记录,暂不加入保留列表
        if ($previousRecvByts -eq $null) {
            $previousRecvByts = $currentRow.RecvByts
            $previousRow = $currentRow
            continue
        }

        # 判断当前行与上一行RecvByts是否连续重复
        if ($currentRow.RecvByts -eq $previousRecvByts) {
            # 确保上一行未被重复添加
            if (-not $filteredRows.Contains($previousRow)) {
                $filteredRows += $previousRow
            }
            # 添加当前行
            $filteredRows += $currentRow
        }

        # 更新上一行的记录
        $previousRecvByts = $currentRow.RecvByts
        $previousRow = $currentRow
    }

    # 生成过滤后的文件名(原文件名后加_filtered)
    $newFilePath = Join-Path -Path $file.DirectoryName -ChildPath "$($file.BaseName)_filtered.csv"
    # 导出为新CSV文件,去除PowerShell类型信息
    $filteredRows | Export-Csv -Path $newFilePath -NoTypeInformation -Encoding UTF8
    Write-Host "已处理完成:$newFilePath"
}

关键说明

  1. 路径替换:务必将$targetFolder的值改为你的实际CSV文件夹路径
  2. 编码适配:若原CSV使用非UTF8编码,可将Export-Csv的-Encoding参数改为Default(系统默认编码)或Unicode等
  3. 性能优化:如果单个CSV文件体积过大(比如超过1GB),可以改用逐行读取+流写入的方式减少内存占用,示例如下:
# 大文件处理的简化示例(针对单个文件)
$inputPath = "C:\LargeFile.csv"
$outputPath = "C:\LargeFile_filtered.csv"
$reader = New-Object System.IO.StreamReader($inputPath)
$writer = New-Object System.IO.StreamWriter($outputPath)

# 写入表头
$header = $reader.ReadLine()
$writer.WriteLine($header)

$prevRecvByts = $null
$prevLine = $null

while (($line = $reader.ReadLine()) -ne $null) {
    $recvByts = ($line -split ",")[2] # 假设RecvByts是第三列,索引从0开始
    if ($prevRecvByts -ne $null -and $recvByts -eq $prevRecvByts) {
        $writer.WriteLine($prevLine)
        $writer.WriteLine($line)
    }
    $prevRecvByts = $recvByts
    $prevLine = $line
}

$reader.Close()
$writer.Close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:17:42