powershell - 匹配两个不同文件中的字符串并输出此 + 以下行
问题描述
从一份相当复杂的合同中,我有两个 .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
上面的代码还不够匹配,我需要帮助来完成最后的润色!
感谢您阅读我的帖子!
解决方案
- 您的模式锚定在行 begin (
^
) 并且不包括前缀Hash:
。 - 此外,要获取路径,您需要一个多行模式,需要使用 -raw 参数读取文件并
(?sm)
在模式中包含开关。 - 此外,还不清楚一个文件中是否有多个 Hash:/Path: 组合以及从多少文件中提取这些对。
我建议:
- 使用函数来提取信息,或者
- 如果只有两个文件用于
Compare-Object
获取匹配对,或者 - 如果有更多文件,则通过哈希收集输出,
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
推荐阅读
- numpy - How to multiply a NxN matrix H with a Nx1 array t = [t1,t2,...,tN] such that H*t = [H*t1,H*t2,...,H*tN] using numpy?
- image - 配置文件 $HOME/.magick 的格式是什么?
- skype-for-business - 在 Skype for Business Client 中订阅状态更改
- regex - -f 但不是 -F 的正则表达式
- jquery - Jquery Datatables搜索和分页错误的位置
- python - 根据先前定义的函数指定参数定义 python 函数
- spring - 如何创建一个将 HttpServletRequest 作为构造函数参数的 bean?
- python - 具有 SubPalindrom 长度的递归子回文
- c# - 为什么我的 ASP.NET Core 视图出现编码错误?
- apache-nifi - NiFI“无法找到流文件内容”