如何使用Powershell合并和删除CSV文件的重复项

时间:2017-11-06 09:02:17

标签: powershell csv

我想请求您如何使用Powershell删除CSV文件中的重复项。我知道有关于此的帖子,但我似乎无法找到有帮助的帖子。

我正在尝试合并具有相同标头的2个CSV文件,然后根据第一列中列出的ID删除生成的文件的副本,然后将其放到同一个CSV文件中。

该文件的属性如下: enter image description here

当我尝试使用sort和unique方法时,我得到以下内容(不是表格: enter image description here

到目前为止,这是我的代码: enter image description here

####
#MERGE
$getFirstLine = $true
    get-childItem "C:\IGHandover\Raw\IG_INC*.csv"| foreach {
    $filePath = $_
    $lines =  $lines = Get-Content $filePath  
    $linesToWrite = switch($getFirstLine) {
           $true  {$lines}
           $false {$lines | Select -Skip 1}
    }
    $getFirstLine = $false
    Add-Content "C:\IGHandover\new.csv" $linesToWrite
    }

####
#REMOVE DUPLICATES
Import-Csv "C:\IGHandover\new.csv" | Sort inc_number -Unique |
    Set-Content "C:\IGHandover\new.csv"

我对Powershell真的很新,并且很想学习不同的技巧。我真的很感谢你对此的帮助。

谢谢!

3 个答案:

答案 0 :(得分:1)

请勿使用Get-Content或Set-Content导入或导出csv文件

Import-Csv (Get-ChildItem 'C:\IGHandover\Raw\IG_INC*.csv') |         
        Sort-Object -Unique inc_number |
            Export-Csv 'C:\IGHandover\new.csv' -NoClobber -NoTypeInformation

答案 1 :(得分:0)

我想您想要使用新表(HandoverINC.csv)中的记录更新表(New.csv),用HandoverINC.csv替换相同主键({{inc_number中的所有记录1}})来自New.csv中的HandoverINC.csv。并将New.csv中的所有新记录添加到HandoverINC.csv(基本上在SQL中称为Full Join)。

使用https://stackoverflow.com/a/45483110/1701026

中描述的Join-Object
Import-CSV .\HandoverINC.csv | FullJoin (Import-CSV .\New.csv) inc_number {$Right.$_} | Export-CSV .\HandoverINC.csv

答案 2 :(得分:0)

根据Lieven Keersmaekers和Vivek Kumar的建议,我在代码中做了一些更改:

  • 将合并的内容放入临时文件
  • 导入包含合并内容的csv文件
  • 对参考列进行排序并使用唯一参数
  • 将结果导出到新的csv文件

我发现我的代码与Vincent K的相似:

#MERGE
$getFirstLine = $true
get-childItem "C:\IGHandover\Raw\IG_INC*.csv"|
foreach {
    $filePath = $_
    $lines =  $lines = Get-Content $filePath  
    $linesToWrite = switch($getFirstLine) {
    $true  {$lines}
    $false {$lines | Select -Skip 1}}
    $getFirstLine = $false
    Add-Content "C:\IGHandover\HandoverINCtemp.csv" $linesToWrite }

#REMOVE DUPLICATES
Import-Csv "C:\IGHandover\HandoverINCtemp.csv" | Sort inc_number -Unique |
    Export-Csv "C:\IGHandover\HandoverINC.csv" -NoClobber -NoTypeInformation -Force
    Remove-Item "C:\IGHandover\HandoverINCtemp.csv"

简化(合并和删除具有相同标题的重复项),如Vincent所建议的那样:

Import-Csv (Get-ChildItem "C:\IGHandover\Raw\IG_INC*.csv") | Sort inc_number -Unique |
    Export-Csv "C:\IGHandover\HandoverINC.csv" -NoClobber -NoTypeInformation -Force

我希望这可以帮助任何想要对文件做同样事情的人

相关问题