[英]How to merge and remove duplicates of CSV files using Powershell
我想請您提供有關如何使用Powershell刪除CSV文件中重復項的幫助。 我知道已經有關於此的帖子,但是我似乎找不到有幫助的帖子。
我正在嘗試合並2個具有相同標題的CSV文件,然后根據第一列中列出的ID刪除結果文件的重復項,然后將其放入相同的CSV文件中。
當我嘗試使用sort和unique方法時,得到以下內容(不是表:
####
#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真的很陌生,很想學習不同的技術。 非常感謝您的幫助。
謝謝!
不要使用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
我猜你想更新表( HandoverINC.csv
從一個新的表(記錄) New.csv
),取代在任何記錄HandoverINC.csv
具有相同主鍵( inc_number
從) New.csv
在HandoverINC.csv
。 並將New.csv
中的任何新記錄添加到HandoverINC.csv
(基本上在SQL中稱為完全連接 )。
使用https://stackoverflow.com/a/45483110/1701026中描述的Join-Object
Import-CSV .\HandoverINC.csv | FullJoin (Import-CSV .\New.csv) inc_number {$Right.$_} | Export-CSV .\HandoverINC.csv
正如Lieven Keersmaekers和Vivek Kumar所建議的那樣,我對代碼進行了一些更改:
我發現我的代碼類似於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
希望這對希望對文件進行相同處理的人有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.