You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扫描LDIF文件提取指定DN与APNID字段生成逗号分隔行?

处理LDIF文件提取指定DN与APNIDx字段的解决方案

针对数百万条记录的LDIF文件,推荐使用awk工具处理,它逐行读取文件、内存占用低,适合大文件场景:

awk实现方案

awk '/^dn: serv=CSPS/ {dn=$0} /^APNID([1-9]|[1-3][0-9]|40):/ {split($0, arr, ": "); print dn "," arr[1] "," arr[2]}' input.ldif > output.csv

代码说明

  • /^dn: serv=CSPS/ {dn=$0}:捕获以dn: serv=CSPS开头的行,将整行内容存入变量dn
  • /^APNID([1-9]|[1-3][0-9]|40):/:精确匹配APNIDx:(x为1-40)的行,避免匹配超出范围的字段
  • split($0, arr, ": "):将当前行按: 分割为数组,arr[1]是字段名(如APNID10),arr[2]是对应数值
  • print dn "," arr[1] "," arr[2]:拼接DN、字段名、数值,以逗号分隔输出到结果文件

Python实现方案(适合需扩展逻辑场景)

如果需要后续扩展处理逻辑,可使用Python逐行读取文件,避免加载大文件到内存:

import re

# 定义匹配规则
dn_regex = re.compile(r'^dn: serv=CSPS.*')
apn_regex = re.compile(r'^APNID([1-9]|[1-3][0-9]|40): (.*)')

current_dn = ""

# 逐行处理文件
with open('input.ldif', 'r') as in_file, open('output.csv', 'w') as out_file:
    for line in in_file:
        line = line.strip()
        if not line:
            continue  # 跳过LDIF记录间的空行
        
        # 更新当前匹配的DN
        dn_match = dn_regex.match(line)
        if dn_match:
            current_dn = line
            continue
        
        # 提取APNIDx字段并输出
        apn_match = apn_regex.match(line)
        if apn_match and current_dn:
            field = f"APNID{apn_match.group(1)}"
            value = apn_match.group(2)
            out_file.write(f"{current_dn},{field},{value}\n")

使用说明

  1. 将上述代码中的input.ldif替换为你的实际文件名
  2. 运行命令后,结果会保存到output.csv文件中

内容的提问来源于stack exchange,提问作者Sergio Jimenez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:35:33