如何在PowerShell中按规则拆分文本文件并关联包与文件
解决方案
你的分段思路完全可行,我们可以把文件按Package File:拆分,构建一个包名-文件列表的映射字典,之后就能高效实现你的查询需求。以下是具体实现步骤和Python示例代码:
1. 解析文件构建映射
先读取目标文件,逐行解析出每个包对应的所有文件:
def build_package_file_map(file_path): package_map = {} current_package = None current_files = [] with open(file_path, 'r') as f: for line in f: line = line.strip() if not line: continue # 匹配Package File行,提取去掉前缀/的包名 if line.startswith('Package File:'): # 保存上一个包的文件列表 if current_package is not None: package_map[current_package] = current_files.copy() current_files.clear() # 提取包名:去掉开头的"Package File: /" current_package = line.split('/')[-1] # 匹配File行,提取文件名(去掉${TargetRootFolder}/前缀) elif line.startswith('File:'): if current_package is not None: file_name = line.split('/')[-1] current_files.append(file_name) # 处理最后一个包的文件列表 if current_package is not None: package_map[current_package] = current_files return package_map
2. 实现查询功能
基于上面的映射字典,实现你需要的查询逻辑:输入文件名,先找包名包含该文件名片段的包,再验证该文件是否属于这些包:
def query_file(package_map, target_file): # 先收集所有包名包含目标文件片段的包 matched_packages = [pkg for pkg in package_map if target_file in pkg] if not matched_packages: print(f"没有包名包含'{target_file}'片段的包") return # 检查目标文件是否在这些包的文件列表中 for pkg in matched_packages: if target_file in package_map[pkg]: print(f"文件'{target_file}'属于包'{pkg}'") else: print(f"包'{pkg}'的包名包含'{target_file}',但该文件不在此包的文件列表中")
3. 使用示例
# 替换为你的文件路径 file_path = 'your_file.txt' package_map = build_package_file_map(file_path) # 查询示例 query_file(package_map, 'Resolver.exe') query_file(package_map, '8_6')
逻辑说明
- 解析时自动跳过空行,只处理有效内容
- 包名自动去掉开头的
/,比如/ForwarderServiceVersion_8_6x会被处理为ForwarderServiceVersion_8_6x - 查询时先匹配包名包含目标片段的项,再逐一验证文件是否属于该包的文件列表
内容的提问来源于stack exchange,提问作者Bandit
相关产品推荐
相关产品推荐

