【问题标题】:Compare column values and merge比较列值并合并
【发布时间】:2021-12-24 04:19:06
【问题描述】:

我正在尝试合并两个具有共同列名的 csv 文件,但一个有 22 行,另一个只有 16 行。

1st CSV                                2nd CSV

Name       Service_StatusA              Name         Service_StatusB 
IEClient     running                   IEClient          Manual
IE Nomad     running                   ​IE Nomad          running
Data Usage   running                   Print Spooler     Manual
Print Spooler running                  Server            running
Server        running

我想把它合并到一个单独的 csv 中

Name           Service_StatusA     Service_StatusB
IEClient          running             Manual
IE Nomad          running             running
Data Usage        running
Print Spooler     running             Manual
Server            running             running
$file1 = Import-Csv -Path .\PC1.csv
$file2 = Import-Csv -Path .\PC2.csv
$report = @()

    foreach ($line in $file1) 
    {
        $match = $file2 | Where-Object {$_.Name -eq $line.Name}
        if ($match)
        {
            $row = "" | Select-Object 'Name','Service_StatusA','Service_StatusA',
            $row.Name = $line.Name
            $row.'Service_StatusA' = $line.'Service_StatusA'
            $row.'Service_StatusB' = $match.'Service_StatusB'
            $report += $row
        }
    }
$report | export-csv .\mergetemp.csv -notype -force

如何在合并前比较行值

【问题讨论】:

标签: powershell powershell-4.0


【解决方案1】:

在 SQL 数据库术语中,您需要左连接,而您的代码正在执行内连接。在设定的条件下,您正在做 1.csv 和 2.csv 的交集(仅出现在两者中的行),但您想要做 1.csv + 交集的并集(来自 1.csv 的所有行仅2.csv 中的匹配行)。

您希望第一个 csv 中的每一行都成为输出 csv 中的一行。那应该是开始 - 总是在你的循环中输出一些东西。目前您从 if() 测试中输出。如果存在,您希望第二个 csv 中的匹配行添加它们的数据,但不要更改输出量。

$file1 = Import-Csv -Path .\PC1.csv
$file2 = Import-Csv -Path .\PC2.csv

$report = foreach ($line in $file1) 
    {
        # always make an output line for each row in file1
        $row = "" | Select-Object 'Name','Service_StatusA','Service_StatusA',
        $row.Name = $line.Name
        $row.'Service_StatusA' = $line.'Service_StatusA'

        # if there is a matching line in file2, add its data in    
        $match = $file2 | Where-Object {$_.Name -eq $line.Name}
        if ($match)
        {
            $row.'Service_StatusB' = $match.'Service_StatusB'                
        }

        # always have output a row for a row in file1
        $row
    }
$report | export-csv .\mergetemp.csv -notype -force

(您可能想要的是一个 SQL 外连接,其中 2.csv 中不在 1.csv 中的行也会创建一个输出行,但您的示例没有显示)。

(我去掉了$report +=,因为它更多的代码运行得更慢,这是一个令人讨厌的组合)。

【讨论】:

  • 谢谢...它成功了。非常感谢。
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 2015-04-02
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
相关资源
最近更新 更多