Powershell - 从分隔的时间/日期列表中删除条目,仅保留每个日期的最早或最新条目?

问题描述 投票:0回答:1

我有两个按时间顺序排序的日期和时间的大型 .csv 文件,用逗号分隔,其结构如下:

27/07/2020,3:39:13 AM
27/07/2020,4:19:05 AM
27/07/2020,4:19:06 AM
27/07/2020,4:19:07 AM
31/07/2020,1:04:02 AM
31/07/2020,1:04:04 AM
6/08/2020,11:46:30 AM
6/08/2020,11:46:31 AM
6/08/2020,12:43:55 PM
6/08/2020,12:43:56 PM

在这两个文件中,我需要将每个日期的条目减少到只有一个,将每个日期的第一个条目保留在一个文件中,将每个日期的最后一个条目保留在另一个文件中。

我尝试使用子字符串和正则表达式来解析文本,然后将其添加到新文件中,但我就是无法正确处理。任何帮助将不胜感激。

powershell date time
1个回答
0
投票

...因为我是个白痴,@Olaf 提供了帮助。有 Mk-III 解决方案。
评论更改背后的动机。

新(我希望是正确的)答案:

进一步改进,谢谢@Olaf

$Top = [System.Collections.ArrayList]::new()
$Bottom = [System.Collections.ArrayList]::new()

# skip -Header parameter if the CSV has headers
$csv = Import-Csv $InputFile -Header date, time 

# Gets a list of the unique dates
$Dates = $csv | Select-Object date -Unique

# For each unique date
foreach ($data in $dates) {
    # on every objects where its Date property is equivalent to the looping date
    $temp = ${csv}.where({ $_.date -eq $data.date }) |
        # orders them by their Time property casted as [Datetime].
    # Sort-Object -Property @{e = { [datetime]::Parse($_.time) } } 
        
    # loads in the ArrayList the first item, which is the lowest==earliest time
    $top.insert(0, ($temp | Select-Object -First 1))
    # loads in the ArrayList the last item, which is the highest==latest time
    $bottom.insert(0, ($temp | Select-Object -Last 1))

}

# add -NoHeader and\or -Append parameters as necessary
$top | Export-Csv $OutTopb
$bottom | Export-Csv $OutBottom

旧错误答案:

如果是没有标题的原始列表\CSV:

Get-Content $FileInput | Select-First 1 | Out-File $FileOutput

如果是带标题的 CSV:

Import-Csv $FileInput | Select-First 1 | Export-Csv $FileOutput

根据需要将

Select-First
替换为
Select-Last
。当然
$FileInput
$FileOutput
可以是相同的

奖励:如果值尚未按顺序排列,您可以在

Sort-Object
\
Select-First
之前将其通过管道传输到
Select-Last

© www.soinside.com 2019 - 2024. All rights reserved.