Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 369
  • Last Modified:

scirpt to compare Text file A with Text file B

Hi Guys,

I need a script that can compare text file A with text file B. If any line in text file A is found in text file B, print that line out onto the screen or into a text file.

it can be vb, powershell, batch.

Please advise.

Thanks
0
fireburn11
Asked:
fireburn11
1 Solution
 
Dale HarrisCommented:
I think there's a really easy command for compare-object for text files.

http://technet.microsoft.com/en-us/library/ee156812.aspx

Compare-Object $(Get-Content c:\scripts\x.txt) $(Get-Content c:\scripts\y.txt)

DH
0
 
Dale HarrisCommented:
Well after looking at what you're doing, I think you're making a list in one file and the output is in the other.

In this case, you could do a simple foreach loop in Powershell to do it.

$matches = get-content "C:\Scripts\FileA.txt"

$output = get-content "C:\Scripts\FileB.txt"

foreach ($match in $matches){
foreach ($line in $output){
if ($match -eq $line){Write-Host $line}
}
}
0
 
Brent ChallisPrincipal: ITCommented:
A more efficient way to implement the check is to test with -contains:

$fileA = get-content "C:\data\Development\Powershell\ScriptQuestion\TextFileA.txt"
$fileB = get-content "C:\data\Development\Powershell\ScriptQuestion\TextFileB.txt"

foreach ($lineA in $fileA)
{
    if ($fileB -contains $lineA)
    {
        Write-Host $lineA
    }
}

When I tested this on two text files of 1000 lines each with 434 matches the -contains version ran approximately 2 1/2 times faster.

If you wanted the output to go to a file rather than the console you could replace

Write-Host $lineA

with
$lineA | Out-File fileName -Append
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Dale HarrisCommented:
Oh, very nice improvement bchallis.  Thanks for testing that.  I knew it wasn't the most efficient either with two foreach loops nested.
0
 
Bill PrewCommented:
Here's how to do it with a simple BAT or command line command:
findstr /i /g:a.txt b.txt

Open in new window

~bp
0
 
fireburn11Author Commented:
Great solution!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now