拆分CSV会在文件末尾留下空行

时间:2018-03-13 09:58:34

标签: powershell

我有以下代码,它接受一个csv文件并根据列值将其拆分。

它可以工作,但它在底部/最后一行留下一个空/新行。我已经尝试过几次调整它以消除空线而没有快乐。你介意看看我错过了什么吗?

$date = Get-Date
$date = $date.ToString("yyyyMMdd")
$src = $PSScriptRoot + "\file_export.csv" 
$dstDir = $PSScriptRoot + ".\files_$date"
New-Item -itemType Directory -Force -Path $dstDir

# Delete previous output files
Remove-Item -Path "$dstDir\*"

# Setup for input data via StreamReader
$inData = New-Object -TypeName System.IO.StreamReader -ArgumentList $src

# Initialize the current file name
$currentFile = ""

while ($line = $inData.ReadLine())
{
    $newFile = "$(($line -split ",")[13])_$date.csv"
    if ($newFile -ne $currentFile)
    {
        # We're starting on a new file
        if ($currentFile -ne "")
        {
            # Write out contents of current file
            $outData.ToString() | Out-File -FilePath $dstDir\$currentFile -Encoding ascii
        }
        # Get ready for a new current file
        $currentFile = $newFile
        $outData = New-Object -TypeName System.Text.StringBuilder
        #[void]$outData.Append($header)
    }

    Write-Verbose "$currentFile, $line"
    [void]$outData.AppendLine($line)

} # end main while loop - done reading input

2 个答案:

答案 0 :(得分:0)

您可以尝试仅解析并输出非空或空的$line,如:

while ($line = $inData.ReadLine())
{
    if(-not ([String]::IsNullOrEmpty($line))) {
        $newFile = "$(($line -split ",")[13])_$date.csv"

        ...

        Write-Verbose "$currentFile, $line"
        [void]$outData.AppendLine($line)
    } # end if string is null or empty
} # end main while loop - done reading input

答案 1 :(得分:0)

谢谢大家的帮助,以下代码解决了问题

$outData.ToString() | Out-File -FilePath $dstDir\$currentFile -Encoding ascii -NoNewLine