[英]How can I use Powershell to compare two CSV files, then update the one of the CSV files with results of comparison
我想比較兩個 CSV 文件“主”和“輸入”,然后更新“主”文件以使其包含差異
“主”文件最初將包含一些數據......像這樣:
A,B,C
5,9,cat
1,2,dog
2,8,rabbit
8,8,mouse
6,2,duck
“輸入”文件可能包含來自主文件的條目,需要更新、沒有更改或已添加:
A,B,C
1,2,otter
8,8,mouse
5,3,tiger
現在,比較主文件和輸入文件,結果如下:
更新
master 和 input 之間存在差異,1,2 master 文件包含:1,2, dog輸入文件包含 1,2, otter ,需要更新 master 文件
沒變
主AND輸入文件包含:8,8,mouse,所以什么都不做
添加
輸入文件包含一個新條目5,3,tiger ,因此主文件將附加該新數據
結果主文件
A,B,C
5,9,cat
1,2,otter
2,8,rabbit
8,8,mouse
6,2,duck
5,3,tiger
這是我擁有的代碼:
$apples = Get-Content $Input
$oranges = Get-Content $Master
# this will generate the file that contains ONLY the CHANGED or new entries that must be recorded
Compare-Object $apples $oranges -PassThru | Where-Object{ $_.SideIndicator -eq "<=" } | Out-File $OutFile
# this will generate the file that contains the old entries that need to be replaced with the new ones
Compare-Object $apples $oranges -PassThru | Where-Object{ $_.SideIndicator -eq "=>" } | Out-File $FixUp
這就是我被卡住的地方......我可以獲得“修復”和“舊”條目......但我不知道如何使用它們來更新主文件?
我正在考慮遍歷文件……但后來想……我如何將主文件與修復更改相關聯:
$csv = Import-Csv $FixUp
#This works fine
for($i = 0; $i -lt @($csv).Length; $i++){
#$find = how do i get old csv value from master file ???
#$replace = $csv
#(Get-Content $file).replace($find, $replace) | Set-Content $file
}
如果您將輸入數據視為 CSV 數據,您可以選擇Compare-Object
應該用於比較的屬性。
$Apples = @'
A,B,C
5,9,cat
1,2,dog
2,8,rabbit
8,8,mouse
6,2,duck
'@ |
ConvertFrom-Csv
$Oranges = @'
A,B,C
1,2,otter
8,8,mouse
5,3,tiger
'@ |
ConvertFrom-Csv
Compare-Object -ReferenceObject $Oranges -DifferenceObject $Apples -Property A, B -IncludeEqual -PassThru
結果會是這樣:
A B C SideIndicator
- - - -------------
1 2 otter ==
8 8 mouse ==
5 9 cat =>
2 8 rabbit =>
6 2 duck =>
5 3 tiger <=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.