如何使用PowerShell在CSV文件中插入空行?

时间:2016-12-18 17:06:02

标签: powershell csv

CSV-文件:

DateColumn;ValueColumn
<Date1>;<Value1>
<Date2>;<Value2>
<Date3>;<Value3>
...

我想要做的是将dateX的日期与dateX + 1的日期进行比较,如果它们不相等,我想在这两个日期之间添加一个空行。 我该如何添加空行?

代码:

$content = Import-Csv -LiteralPath 'C:\test.csv' -Delimiter ';'
$counter = 1
$dateOne = $null
$dateTwo = $null

foreach ($row in $content) {
    if ($counter -gt 1) {
        $dateTwo = $row.DateColumn -as [DateTime]
        if ($dateOne.Day -ne $dateTwo.Day) {
            "`n" + $row | Add-Content 'C:\test.csv' | Set-Content 'C:\test.csv'
            $dateOne = $dateTwo
        }
    } else {
        $dateOne = $row.DateColumn -as [DateTime]
    }
    $counter = $counter + 1
}

我得到的输出在CSV文件中是这样的:

@{DateColumn=29.01.2004 12:29, ValueColumn=2,2}

@{DateColumn=30.01.2004 12:29, ValueColumn=2,5}

@{DateColumn=31.01.2004 12:29, ValueColumn=2,8}

它将它附加到现有数据,不会覆盖。有什么建议吗?

期望的输出:

29.01.2004 12:29       2,2

30.01.2004 12:29       2,5

31.01.2004 12:29       2,8

2 个答案:

答案 0 :(得分:2)

你认为太复杂了。只需这样做:

$prev    = $null
$current = $null
Get-Content 'C:\path\to\input.csv' | Select-Object -Skip 1 | ForEach-Object {
    # extract date from current record
    $current = ($_ -split ';')[0] -as [DateTime]

    # print empty line if date changed from previous line
    if ($prev -and $prev.Date -ne $current.Date) { "`n" }

    # print current line
    $_ -replace ';', "`t"

    # remember date from this iteration in the next iteration
    $prev = $current
} | Set-Content 'C:\path\to\output.txt'

答案 1 :(得分:0)

其他解决方案,使用select-string及其上下文选项

select-string -Path "C:\temp\New.txt" -Pattern "." -Context 1, 0 | %{
if ($_.Context.PreContext[0] -like "DateColumn*")
{
$_.line
}

elseif ($_.line -notlike "DateColumn*" -and ($_.line -split ";")[0] -ne ($_.Context.PreContext[0] -split ";")[0])
{
  $_.Line ; ";"
}
else
{
$_.Line 
}
} | Set-Content "C:\temp\New2.txt"