【问题标题】:Match Strings in two different files and output this + following line匹配两个不同文件中的字符串并输出此 + 以下行
【发布时间】:2019-07-21 00:56:46
【问题描述】:

从一份相当复杂的合同中,我有两个 .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

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

感谢您阅读我的帖子!

【问题讨论】:

  • "上面的代码还不够匹配" - 请包括 1) 你期望发生的事情,2) 实际发生的事情,以及 3) 修复语法不正确/不完整的代码 sn-p

标签: powershell


【解决方案1】:
  • 您的模式锚定在行开头 (^) 并且不包括前缀 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2021-11-10
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多