Powershell比较文件

时间:2016-02-24 07:37:23

标签: powershell

我是一个使用PowerShell的新人。在这里,我有一个任务来比较两个文件。文件格式如下:

文件A.txt

20160222|LineA
20160222|LineB
20160222|LineC

文件B.txt

20160223|LineE
20160223|LineA
20160223|LineD
20160223|LineB
20130223|LineC

经过比较,我想找出

20160223|LineE
20160223|LineD

作为第三个输出文件。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

好的,所以这有点令人费解,但会完成工作。

# Split the date and value, but keep the raw value intact
$fileA = Get-Content .\fileA.txt | Select-Object -Property @{ Name="Value"; Expression={ $_.Substring($_.IndexOf("|")+1) }}, @{ Name="Raw"; Expression={ $_ }}
$fileB = Get-Content .\fileB.txt | Select-Object -Property @{ Name="Value"; Expression={ $_.Substring($_.IndexOf("|")+1) }}, @{ Name="Raw"; Expression={ $_ }}

# Find the differences, should contain LineE and LineD
$diffs = Compare-Object -ReferenceObject $fileA -DifferenceObject $fileB -Property Value | Select-Object -Expand Value

# Match the diffs against original content and pull out the raw values
$fileB | Where-Object { $diffs -contains $_.Value } | Select-Object -Expand Raw

答案 1 :(得分:1)

这更像是期望的结果:

$a = Import-Csv .\a.txt -Delimiter "|" -Header 'no', 'line'
$b = Import-Csv .\b.txt -Delimiter "|" -Header 'no', 'line'

$c = Compare-Object -ReferenceObject $a -DifferenceObject $b -Property line


$z =@()
foreach ($d in $c)
{
    if ($d.SideIndicator -eq "=>")
    {
        $z += $b | ?{$_.line -eq $d.line}
    }
    else  # <=
    {
        $z +=$a | ?{$_.line -eq $d.line}
    }
}

结果:

$z | % { write-host "$($_.no)|$($_.line)"}
20160223|LineE
20160223|LineD