Home > Software design >  PS - Check if a text file contains lines from another file and return found line
PS - Check if a text file contains lines from another file and return found line

Time:01-12

i want to check FileA.txt if it contains lines from FileB.txt and if yes it should return that line in which the line from FileB was found.

FileA contains the filenames of a directory, FileB is a .log file from a fax software.

FileA looks like this:

2235375.pdf
2436317.pdf
1234245.pdf

FileB looks like this:

date_time_faxnumber_status_filename.pdf

I tried to use Compare-Object

Get-ChildItem -Path P:\Fax -Name | Out-File -FilePath P:\Fax\Data.txt -Encoding oem -Force

Get-ChildItem P:\Fax\OUT* -Include *.log |  
        Sort-Object -Property LastWriteTime | 
            Select-Object -Last 1 | 
                Copy-Item -Destination P:\Fax\Fax.txt -Force


$Content1 = Get-Content Data.txt
$Content2 = Get-Content Fax.txt
Compare-Object $Content2 $Content1 | ? {$_.Sideindicator -eq "="} | Out-File "P:\Fax\Output.txt" -Force

I'm stuck at the compare line from FileA to FileB and if found return that line from FileB. I would like to have some hint in which direction i have to change my code

CodePudding user response:

Compare-Object requires the values from both objects to match exactly, so it won't do text comparisons like you need. The simple way is to check each line of FileA for each line of FileB which can be done like so:

$Content1 = Get-Content FileA.txt
$Content2 = Get-Content FileB.txt
$result = Foreach ($filename in $Content1) {
  Write-Output $filename
  $Content2 | Where-Object {$_ -Like "*$filename"}
}

$result

The result should look like this, useful if you have multiple log lines per filename:

2235375.pdf
date_time_faxnumber_status_2235375.pdf
2436317.pdf
20220101_010000_0001_SUCCESS_2436317.pdf
1234245.pdf
20220101_020000_0002_ERROR_1234245.pdf
20220101_030000_0003_SUCCESS_1234245.pdf

It's not the most efficient way, but should do what you're looking for

CodePudding user response:

For this, I would use the Select-String cmdlet which is able to

  • Search for multiple patterns in once
  • Stream the input (log) file contents
  • Highlight the matches

$Pattern = Get-Content .\FileA.txt # Loads an array of strings (lines)
.\FileB.txt |Select-Object $Pattern -SimpleMatch

Note: the highlighting when the output is passed to a file

  •  Tags:  
  • Related