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

PowerShell处理CSV文件:按日期保留最早或最晚时间条目

处理按时间排序的CSV:保留每日首/末条目

因为你的CSV已经按时间顺序排好,直接遍历处理就能高效完成需求,不需要额外排序或复杂解析,以下是两个PowerShell脚本:

保留每个日期的第一条条目

$inputFile = "你的输入文件路径.csv"
$outputFile = "每日第一条输出.csv"
$currentDate = $null

Get-Content $inputFile | ForEach-Object {
    # 分割日期和时间部分,确保鲁棒性
    $parts = $_ -split ',', 2
    $date = $parts[0].Trim()
    # 遇到新日期时写入该行,并更新当前记录的日期
    if ($date -ne $currentDate) {
        $_ | Out-File -Append -FilePath $outputFile -Encoding utf8
        $currentDate = $date
    }
}

保留每个日期的最后一条条目

$inputFile = "你的输入文件路径.csv"
$outputFile = "每日最后一条输出.csv"
$currentDate = $null
$lastLine = $null

Get-Content $inputFile | ForEach-Object {
    $parts = $_ -split ',', 2
    $date = $parts[0].Trim()
    if ($date -eq $currentDate) {
        # 同一日期时,持续更新最后一行记录
        $lastLine = $_
    } else {
        # 切换日期时,写入上一日期的最后一行
        if ($lastLine -ne $null) {
            $lastLine | Out-File -Append -FilePath $outputFile -Encoding utf8
        }
        $currentDate = $date
        $lastLine = $_
    }
}
# 写入最后一个日期的最后一行
if ($lastLine -ne $null) {
    $lastLine | Out-File -Append -FilePath $outputFile -Encoding utf8
}

注意事项

  • 替换脚本中的你的输入文件路径.csv和输出文件路径为实际路径
  • 如果原文件编码不是UTF-8,可调整-Encoding参数为对应编码(如default、unicode)
  • 脚本直接用字符串比较日期,无需解析为日期对象,处理大型文件时效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:31