AIX系统中用Awk替代不支持的grep -B匹配指定软件包记录
AIX下用Awk替代grep -B匹配软件包对应漏洞行及版本行
问题背景
AIX系统不支持grep -B参数,需用Awk实现:从包含漏洞描述与软件包版本的文件中,提取指定软件包(如openssl.base)对应的前一行漏洞描述和当前软件包版本行。
示例文件内容
05/25/2025 M 301510sa AIX is vulnerable to information disclosure (CVE-2024-13176) or arbitrary code execution or a denial of service (CVE-2024-9143) due to OpenSSL openssl.base 3.0.15.1000 < 3.0.15.1001 06/15/2025 M 973013sab AIX is vulnerable to a denial of service (CVE-2025-26466) and a machine-in-the-middle attack (CVE-2025-26465) due to OpenSSH openssh.base.server 9.7.3013.1000 < 9.7.3013.1001 06/15/2025 M 973013saa AIX is vulnerable to a denial of service (CVE-2025-26466) and a machine-in-the-middle attack (CVE-2025-26465) due to OpenSSH openssh.base.client 9.7.3013.1000 < 9.7.3013.1001
期望输出
05/25/2025 M 301510sa AIX is vulnerable to information disclosure (CVE-2024-13176) or arbitrary code execution or a denial of service (CVE-2024-9143) due to OpenSSL openssl.base 3.0.15.1000 < 3.0.15.1001
原命令无效原因
原命令中/var1/是直接匹配字符串"var1",而非引用变量var1的值,导致无法正确匹配目标软件包:
pkg="openssl.base"; awk -v var1="$pkg" '/var1/{for(i=1;i<=x;)print a[i++];print}{for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}' x=1 file
正确解决方案
方案1:缓存前一行匹配输出
利用Awk的getline读取下一行,结合变量匹配实现需求,通用型强:
pkg="openssl.base" awk -v target="$pkg" '{ prev_line = $0; getline; if ($0 ~ target) { print prev_line; print $0 } }' your_file.txt
方案2:利用文件行规律匹配(更严谨)
观察文件可知:奇数行是漏洞描述,偶数行是软件包信息,直接按行号分组匹配:
pkg="openssl.base" awk -v target="$pkg" 'NR % 2 == 1 { vuln_line = $0 } NR % 2 == 0 && $2 == target { print vuln_line; print $0 }' your_file.txt
说明
- 方案1适用于行分组不固定的场景;
- 方案2利用文件固定的两行一组规律,匹配更精准,避免误匹配其他行的同名字符串。
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

