【问题标题】:Powershell - trying to compare-object of two columns and write differencePowershell - 尝试比较两列的对象并写入差异
【发布时间】:2018-02-13 04:22:58
【问题描述】:

希望你能帮忙!我一直在尝试使用 compare-object 命令并取得了不同程度的成功,但与我需要的完全不同。我开始认为也许比较不是答案。

我有两个 CSV 文件:RESULTS1 和 RESULTS2

RESULTS1 有几列带有标题...

DATE DAY    LETTER  CAR         NUMBER  NEW

RESULTS2 有两列带有标题...

CAR COLOUR

这是我想要实现的输出... 仅使用 CAR 列,从 RESULTS1 中识别汽车并从 RESULTS2 中的 CAR 列中删除它们(作为重复项)(即,如果福特在两个 CSV 中都列出,请不要'不在输出中显示)。输出将列出 CAR 列中的剩余汽车。我仍然需要打印(作为输出 CSV)如下四列……(或者至少,今天的日期、日期和 CAR)。

DATE        DAY  LETTER CAR

【问题讨论】:

标签: powershell


【解决方案1】:
# put this script in the same folder as the 2 csv files
$results1 = (Get-ChildItem | where name -Match "RESULTS1.csv").FullName
$results2 = (Get-ChildItem | where name -Match "RESULTS2.csv").FullName
$csv1 = Import-Csv $results1 # imports the RESULTS1.csv
$csv2 = Import-Csv $results2 # imports the RESULTS2.csv
$cars1 = @() # car names from 1st csv
$cars2 = @() # car names from 2nd csv
foreach ($line in $csv1)
{$cars1 += ($line.CAR).Trim()}
foreach ($line in $csv2)
{$cars2 += ($line.CAR).Trim()}
$unique = Compare-Object $cars1 $cars2
$unique_cars = ($unique).InputObject # unique cars

$results3 = @()
foreach ($line in $csv2) {foreach ($car in $cars1) 
    { if ($line -notcontains $car) {if ($results3 -notcontains $line) {$results3 += $line} } }
} $results3 

我用我的 2 个标题相同的 csv 文件测试了这个脚本。你可以改变

if ($line -notcontains $car)

if ($line -contains $car)

如果你想要相反的结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2018-01-12
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多