大家好,我一直在使用这个脚本:
perl -F',\s+' -lane '
@ARGV and $h{$F[1]}=$F[0],next;
/^Device ID:\s+(\S+)/ && $h{$a=$1} .. /^$/ || eof() and do{
/^$/ || eof() and $_ = "SN: $h{$a}" . ( eof() ? "" : "\n" );
};
print;
' dispositivoss.csv dispositivos.dat>dispositivoss.dat
它使用这两个文件。
dispositivoss.csv:
serial_number,device_id,ip_address
FOC1518Z1G2, Arq_Laboratorios_EdifB, 148.000.000.248
FOC1216U136, Arquitectura_Dir, 148.000.000.252
FOC1352V3F3, Arq.245, 148.000.000.245
FDO1129Z9Z5, Barragan_3750, 148.000.000.254
dispositivos.dat:
Device ID: Arq_Laboratorios_EdifB
IP address: 148.000.000.248
Interface: FastEthernet0/48
Port ID (outgoing port): GigabitEthernet1/0/48
Device ID: SEP0c1167231895
IP address: 148.000.000.45
Interface: FastEthernet0/4
Port ID (outgoing port): Port 1
Device ID: Arquitectura_Dir
IP address: 148.000.000.252
Interface: GigabitEthernet0/2
Port ID (outgoing port): GigabitEthernet0/1
Device ID: ARQUITECTURA_01
IP address: 148.000.000.21
Interface: FastEthernet0/1
Port ID (outgoing port): FastEthernet0
Device ID: Arq.245
IP address: 148.000.000.245
Interface: FastEthernet0/42
Port ID (outgoing port): GigabitEthernet0/1
Device ID: Barragan_3750
IP address: 148.000.000.254
Interface: GigabitEthernet0/1
Port ID (outgoing port): GigabitEthernet1/0/3
一切都很顺利,但最后,脚本写SN
了Port ID
:
Device ID: Arq_Laboratorios_EdifB
IP address: 148.000.000.248
Interface: FastEthernet0/48
Port ID (outgoing port): GigabitEthernet1/0/48
SN: FOC1518Z1G2
Device ID: SEP0c1167231895
IP address: 148.000.000.45
Interface: FastEthernet0/4
Port ID (outgoing port): Port 1
Device ID: Arquitectura_Dir
IP address: 148.000.000.252
Interface: GigabitEthernet0/2
Port ID (outgoing port): GigabitEthernet0/1
SN: FOC1216U136
Device ID: ARQUITECTURA_01
IP address: 148.000.000.21
Interface: FastEthernet0/1
Port ID (outgoing port): FastEthernet0
Device ID: Arq.245
IP address: 148.000.000.245
Interface: FastEthernet0/42
Port ID (outgoing port): GigabitEthernet0/1
SN: FOC1352V3F3
Device ID: Barragan_3750
IP address: 148.000.000.254
Interface: GigabitEthernet0/1
SN: FDO1129Z9Z5
我该如何保留Port ID
?,有时dispositivos.dat
只有一个设备信息,也会发生同样的情况。
谢谢。
答案1
更改线路:
$_ = "SN: $h{$a}" . ( eof() ? "" : "\n" );
到
$_ .= (eof() ? "\n" : "") . "SN: $h{$a}" . ( eof() ? "" : "\n" );
答案2
perl -F',\s+' -l -00nae '
@ARGV and %h = (%h, reverse(/^(.*?),\s*(.*),/mg)),next;
/^Device ID:\s+(\S+)/ && exists $h{$a=$1} && s/$/\nSN: $h{$a}/;
print $_, eof() ? "": "\n";
' dispositivoss.csv dispositivos.dat > dispositivoss.dat
当您一次查看一个段落的数据时。