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

求助:使用awk数组匹配DisplayLink并提取指定目标行的方法

问题场景与需求

原始设备信息文本如下:

USB2.1 Hub:

          Product ID: 0x0610

            Dell Universal Dock D6000:

              Product ID: 0x6006
              Vendor ID: 0x17e9  (DisplayLink (UK) Ltd.)
              Version: 31.27
              Serial Number: 1810132665
              Speed: Up to 5 Gb/s
              Manufacturer: DisplayLink

需求:当检测到Manufacturer: DisplayLink时,返回两个Product ID行之间的设备名称行(即Dell Universal Dock D6000:)。

原尝试的问题

你之前用awk数组实现的命令存在语法错误:

awk '/DisplayLink/ { for(i=NR-8;i<NR;i++) if(i>0) print a[i]; print; exit} {a[NR}=$0}'

错误点在于数组赋值部分的a[NR}少了闭合的],正确写法应为a[NR];另外硬编码NR-8的行数偏移方式不够可靠,文本格式稍有变动就会失效。

正确的awk数组实现方案

以下两种方式都能通过awk数组实现需求,且不依赖固定行数:

方案一:回溯查找目标行

{ a[NR] = $0 }  # 用数组记录所有行
/Product ID:/ { last_product_id = NR }  # 记录最近的Product ID行号
/Manufacturer: DisplayLink/ {
    # 从最近的Product ID行往前找,定位设备名称行
    for(i=last_product_id-1; i>0; i--) {
        if (a[i] ~ /:$/ && a[i] !~ /Product ID:/) {
            print a[i]
            exit
        }
    }
}

方案二:实时记录设备名称

{ a[NR] = $0 }  # 用数组记录所有行
# 匹配以冒号结尾、非Product ID的设备名称行,实时更新记录
/^[[:space:]]*[^[:space:]]/ && $0 ~ /:$/ && !/Product ID:/ {
    device_name = $0
}
# 匹配到目标Manufacturer时,输出记录的设备名称
/Manufacturer: DisplayLink/ {
    print device_name
    exit
}
说明

这两种awk方案都比你之前用的grep "Manufacturer: DisplayLink" -B7 -n | head -1 | awk -F'[ :]+' '{ $1=""; print $0 }'工具链更灵活,不需要依赖固定的回溯行数,能适配格式小范围变动的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:37:36