首页 > 解决方案 > 匹配两个不同文件中的字符串并输出此 + 以下行

问题描述

从一份相当复杂的合同中,我有两个 .txt 文件。这些文件如下所示:

文件1:

Hash: 5FD876CDF0FCFAF1E7F018F5A8519A7B

Path: /Users/foobar/Desktop/whatever.jpg

文件2:

Hash: 0EDEFB152D489163E603F8C55F5463A7

Path: c:\Migration\Templates\script.exe

这里的目标是比较 File1 和 File2 并找到匹配的哈希。找到匹配的哈希后,将它们(和以下路径)输出到另一个 .txt 文件中。

我已经过度搜索了这个问题,但是大多数解决方案都是为了找到差异或设计不同,我在 Powershell 方面的专业知识还不足以能够正确地重写它们。

# pattern to match the Hashes from File2
$pattern = "^[a-f0-9]{32}$"

# read in File1 as an array to compare to
$set1 = Get-Content -Path 'C:\File1.txt'

# prepare to collect the results
$results = New-Object -TypeName System.Text.StringBuilder

# start scanning the text2 file for matches to text1 entries
Get-Content -Path 'C:\File2.txt'
if ($_ -match $pattern)
   {
        $hashes = $Matches['hash']
        if ($hashes -in $set1)
        {
            [void]$results.AppendLine($_)
        }
    }
}

# output the results
$results.ToString() | Out-File -FilePath 'C:\output.txt' -Encoding ascii

上面的代码还不够匹配,我需要帮助来完成最后的润色!

感谢您阅读我的帖子!

标签: powershell

解决方案


  • 您的模式锚定在行 begin ( ^) 并且不包括前缀Hash:
  • 此外,要获取路径,您需要一个多行模式,需要使用 -raw 参数读取文件并(?sm)在模式中包含开关。
  • 此外,还不清楚一个文件中是否有多个 Hash:/Path: 组合以及从多少文件中提取这些对。

我建议:

  • 使用函数来提取信息,或者
    1. 如果只有两个文件用于Compare-Object获取匹配对,或者
    2. 如果有更多文件,则通过哈希收集输出,Group-Object如果每个组的计数超过 1 个,则输出具有所有路径的组。

以下脚本从给定文件中提取哈希/路径对并将它们作为 [PSCustomObject] 输出。

## Q:\Test\2019\07\20\SO_57124977.ps1

function Extract-HashPath($filename){
    $Pattern = '(?sm)^Hash: (?<Hash>[0-9A-F]{32})(\r?\n)*Path: (?<Path>.*?)$'
    ((Get-Content $filename -raw) | 
        Select-String -Pattern $Pattern -AllMatches).Matches.Groups | ForEach-Object{
            Set-Variable -Name $_.Name -Value $_.Value
            if ($_.Name -eq 'Path'){
                [PSCustomObject]@{
                    Hash = $Hash
                    Path = $Path
                }
            }
        }

}

$File1HashPath = Extract-HashPath '.\File1.txt'
$File2HashPath = Extract-HashPath '.\File2.txt'
$File1HashPath
$File2HashPath

带有上述文件中文本的示例输出(其中不包含可比较的哈希)

> Q:\Test\2019\07\20\SO_57124977.ps1

哈希路径
---- ----
5FD876CDF0FCFAF1E7F018F5A8519A7B /Users/foobar/Desktop/whatever.jpg
0EDEFB152D489163E603F8C55F5463A7 c:\Migration\Templates\script.exe

推荐阅读