Leo
Leo

Reputation: 313

Powershell to compare files

I am a new one to use powershell. Here I have one task to compare two files. The file format like this:

File A.txt

20160222|LineA
20160222|LineB
20160222|LineC

File B.txt

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

After comparing, I want to find out

20160223|LineE
20160223|LineD

as the third output file.

How can I do this?

Upvotes: 0

Views: 114

Answers (2)

Jake Bruun
Jake Bruun

Reputation: 1323

Okay, so this is a bit convoluted, but will get the job done.

# 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

Upvotes: 3

Martin
Martin

Reputation: 1963

Thats more like the desired result :

$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}
    }
}

Result:

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

Upvotes: 1

Related Questions