【问题标题】:powershell: compare specific columns of CSV files and return entire row of differencespowershell:比较CSV文件的特定列并返回整行差异
【发布时间】:2015-10-29 14:22:44
【问题描述】:

我有 2 个 CSV 文件要比较。它们都有多列不同的数据,但它们也都有一个带有 IP 地址的列。称它们为 $log1 和 $log2

我正在尝试比较文件。如果在 $log2 中找到来自 $log1 的 IP,我想要一个输出文件,其中包含来自 $log2 匹配的整行数据...

当我使用时:

Compare-Object -Property 'IP address' -ReferenceObject $log1 -DifferenceObject $log2

它只返回“IP 地址”列和 SideIndicator。

我想我在这里叫错了树,有人可以提供一些建议吗?

【问题讨论】:

  • $log2|Where-Object 'IP address' -in $log1.'IP address'
  • 尝试将-PassThru 标志添加到您的命令中。

标签: csv powershell file-comparison


【解决方案1】:

我会尝试另一种方法:

$log1,$log2 | group-object -Property 'IP address' | where {$_.count -eq 2}

在结果中,您将找到包含两行的 group 属性。

【讨论】:

    【解决方案2】:

    “尝试将 -PassThru 标志添加到您的命令中。” - 戴夫·塞克斯顿

    这行得通。我在打开文件时将结果导出为 CSV 并按 SideIndicator 排序(不要认为您可以让 PS 按 SideIndicator 排序)。

    谢谢戴夫。

    正如其他人所指出的,可能还有更多方法可以实现这一点,但这实现了我的目标。

    【讨论】:

    • 不认为你可以让 PS 按 SideIndicator 排序 sort SideIndicator 不适合你吗?
    【解决方案3】:

    此脚本将比较您的两个 csv 文件并为找到的每个双 ip 地址写入输出。

    #import your csv files
    $csv1 = Import-Csv "C:\Users\Admin\Desktop\csv\csv1.csv"
    $csv2 = Import-Csv "C:\Users\Admin\Desktop\csv\csv2.csv"
    
    #Compare both csv files (.ip corresponds to your column name for your ip address in the csv file )
    $compare = Compare-Object $csv1.ip $csv2.ip -IncludeEqual | ? {$_.SideIndicator -eq "=="}
    
    if ($compare) {
    
        foreach ($ip in $compare.InputObject) {
        Write-Output "IP $ip exist in both csv files"
        }
    
    }
    Else 
        {
            Write-Output "Double ip not found"
        }
    

    【讨论】:

      猜你喜欢
      • 2014-06-08
      • 1970-01-01
      • 2021-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2019-08-24
      • 2019-08-22
      相关资源
      最近更新 更多