我有一个名为 dispositivos.dat 的文件,其中包含与直接连接到某些 cisco 设备的设备相关的所有信息,根据设备的不同,文件会发生变化,这些是该文件的示例:
示例_1:
Device ID: CIVIL_3702-01
IP address: 148.000.000.140
Interface: FastEthernet0/47
Port ID (outgoing port): GigabitEthernet0
Device ID: SEP0c1167231e23
IP address: 148.000.000.149
Interface: FastEthernet0/16
Port ID (outgoing port): Port 1
Device ID: SEP0c116722f331
IP address: 148.000.000.162
Device ID: SEP0c116722f197
IP address: 148.000.000.155
Interface: FastEthernet0/8
Port ID (outgoing port): Port 1
Device ID: Barragan_3750
IP address: 148.000.000.129
Interface: GigabitEthernet0/1
Port ID (outgoing port): GigabitEthernet1/0/11
SN: OPC13020953
示例_2:
Device ID: BIOTERIO
IP address: 148.000.00.189
Interface: GigabitEthernet1/0/6
Port ID (outgoing port): GigabitEthernet0/1
SN: P7K08UQ
Device ID: N7K-LAN(JAF1651ANDL)
IP address: 148.000.0.192
Interface: GigabitEthernet1/0/1
Port ID (outgoing port): Ethernet7/23
SN: H006K022
Device ID: LAB_PESADO
IP address: 148.000.000.130
Interface: GigabitEthernet1/0/11
Port ID (outgoing port): GigabitEthernet0/1
SN: FNS174002FT
Device ID: Arquitectura_Salones
IP address: 148.000.000.61
Interface: GigabitEthernet1/0/9
Port ID (outgoing port): GigabitEthernet0/49
SN: FNS14420533
Device ID: CIVIL_253
IP address: 148.000.000.253
Interface: GigabitEthernet1/0/4
Port ID (outgoing port): GigabitEthernet1/0/52
SN: H006K021
我正在使用 awk 创建包含此信息的 csv 文件,但如您所见,我并不总是拥有所有信息,我对 SN(序列号)特别感兴趣,它是我数据库中的主键,我的 awk 代码是这样的:
awk '
BEGIN {
RS = "\n\n"
FS = "\n"
OFS = ","
print "sn,device_id,ip_address"
}
{
for(i=1; i<=NF; i++) {
split($i, a, ":");
k[a[1]] = a[2]
}
print k["SN"], k["Device ID"], k["IP address"]
}' Example.dat > Example.csv
它适用于Example_2,因为每个设备都有SN:
sn,device_id,ip_address
P7K08UQ , BIOTERIO, 148.000.00.189
H006K022 , N7K-LAN(JAF1651ANDL), 148.000.0.192
FNS174002FT , LAB_PESADO, 148.000.000.130
FNS14420533 , Arquitectura_Salones, 148.000.000.61
H006K021 , CIVIL_253, 148.000.000.253
H006K083 , Arquitectura, 148.000.000.253
H006K032 , ING_CIVIL, 148.000.000.251
FNS16361SG0 , ING_CIVIL_DIR, 148.000.0.188
H006K040 , Ingenieria_Posgrado, 148.000.000.253
00000MTC1444080Z, Biblio_Barragan, 148.000.000.61
FNS11190FLE , Electronica_Edif_3, 148.000.000.253
FDO1129Z9ZJ,Barragan_3750,148.000.0.199
但在Example_1中我得到这个输出:
sn,device_id,ip_address
, CIVIL_3702-01, 148.000.000.140
, SEP0c1167231e23, 148.000.000.149
, SEP0c116722f331, 148.000.000.162
, SEP0c116722f197, 148.000.000.155
OPC13020953 , Barragan_3750, 148.000.000.129
FCQ1622X1GH,LAB_PESADO,148.000.000.130
在Example_1中我需要这样的输出:
sn,device_id,ip_address
OPC13020953 , Barragan_3750, 148.000.000.129
FCQ1622X1GH ,LAB_PESADO,148.000.000.130
我需要避免那些没有 SN 的设备,我需要 awk 代码在任何情况下都能工作。
你可以帮帮我吗?
提前致谢
答案1
非空字符串为 true,因此您只需检查k["SN"]
其真实性即可。另外,我建议k
在循环的开始或结束处清除整个,以避免前一项的值渗透。
因此,将该print
行替换为:
if (k["SN"]) {
print k["SN"], k["Device ID"], k["IP address"]
}
delete k;