Powershell,比较2个txt文件并在txt文件中并排输出差异

时间:2017-04-06 18:54:47

标签: powershell

比较2个txt文件并在txt文件中并排输出差异。

Compare-Object -ReferenceObject $(Get-Content c:\user.txt) -DifferenceObject 
$(Get-Content c:\user_old.txt) | format-table -auto -hidetableheaders  
>C:\user_check.txt

user.txt

 new_id   new_lname   new_fname
   1        Jones       Mike
   2        Lewis       Don
   3        Smith       Melissa
   4        Grady       Sue

user_old.txt

 old_id   old_lname   old_fname
   1        Jones       Mikey
   2        Lewis       Don
   3        Williams    Melissa
   4        Grady       Susan

结果

  old_id   old_lname   old_fname  =>
  1        Jones       Mikey      =>
  3        Williams    Melissa    =>
  4        Grady       Susan      =>
  new_id   new_lname   new_fname  <=
  1        Jones       Mike       <=
  3        Smith       Melissa    <=
  4        Grady       Sue        <=

这就是我想要的

old_id   old_lname   old_fname  =>      new_id   new_lname   new_fname  <=
1        Jones       Mikey      =>      1        Jones       Mike       <=
3        Williams    Melissa    =>      3        Smith       Melissa    <=
4        Grady       Susan      =>      4        Grady       Sue        <=

1 个答案:

答案 0 :(得分:0)

可能不是最干净的方法。但是,既然您知道何时进行比较,那么会有两个输出对象,其中<=SideIndicator,另一个为=>。它们应该按照相同的顺序排列。因此,如果您将它们拆分为两个数组,然后使用相同的索引从两个数组输出一个字符串,您将获得输出字符串。

$compare = Compare-Object -ReferenceObject $(Get-Content c:\temp\user.txt) -DifferenceObject $(Get-Content c:\temp\user_old.txt)
$rights = $compare | ? {$_.sideindicator -eq "=>"}
$lefts = $compare | ? {$_.sideindicator -eq "<="}
foreach ($right in $rights) {
    "$($right.InputObject) `t $($right.SideIndicator)  $($lefts[([array]::indexof($Rights,$right))].InputObject) `t $($lefts[([array]::indexof($Rights,$right))].SideIndicator)"
}