以期在PowerShell中数组减法

问题描述 投票:0回答:3

我有两个CSV格式如下:

A
20180809000
20180809555
20180809666
20180809777
20180809888

文件2:

A
20180809000
20180809555
20180809666
20180809777

我想找到文件1的区别 - 这文件2应该输出20180809888。我试过如下:

$a1= Import-Csv -Path $file1 | select A

$a2 = Import-Csv -Path $file2 | select A

$a1| where {$a2 -notcontains $_}  

但它输出的整个文件1:

A
--------------                                                                                                                       
20180809000                                                                                                                          
20180809555                                                                                                                          
20180809666                                                                                                                          
20180809777                                                                                                                          
20180809888   

我试过路口也有,但是输出空。

powershell powershell-v2.0
3个回答
3
投票

最简单的解决方法是使用:

> Compare-Object (Get-Content .\File1.csv) (Get-Content .\File2.csv) -PassThru
20180809888

或者用进口-CSV

> Compare-Object (Import-Csv .\File1.csv).A (Import-Csv .\File2.csv).A -Passthru
20180809888

要么

> (Compare-Object (Import-Csv .\File1.csv) (Import-Csv .\File2.csv) -Passthru).A
20180809888

1
投票

你的最后一行应该是以下几点:

$a1.A.where{$_ -notin $a2.A}

为了保护之列,你可以做最后一行如下:

$a1.where{$_.A -notin $a2.A}

这种情况的问题是,如果第二档比第一档更多的数据。然后你需要为你的最后一行做这样的事情:

$a1 | compare $a2 | select -expand inputobject

1
投票

select A仍然将与属性命名A返回一个对象。

# Returns an object list with property A
Import-Csv -Path $file | select A # (shorthand for Select-Object -Property A)
# A
# ---
# value1
# value2
# ...

你可以使用点符号,e.g获得财产A的值的数组:

# Returns the list of values of the A property
(Import-Csv -Path $file).A
# value1
# value2
# ...

下面应该工作:

$a1= (Import-Csv -Path $file1).A
$a2 = (Import-Csv -Path $file2).A
$a1 | where {$a2 -notcontains $_}  
© www.soinside.com 2019 - 2024. All rights reserved.