我有两个文件file1和file2。
file1内容:
fc1/20 20:64:00:2a:6a:7d:c8:81 fc1/19 20:b0:00:25:b5:ff:11:02 fc1/18 20:b0:00:25:b5:ff:11:09 fc1/17 20:b0:00:25:b5:ff:11:0b fc1/16 20:b0:00:25:b5:ff:11:0d
file2内容:
20:B0:00:25:B5:FF:11:0D prd-vm32 20:B0:00:25:B5:FF:11:0D prd-vm32 20:B0:00:25:B5:FF:11:0B prd-vm30.bred 20:B0:00:25:B5:FF:11:0B prd-vm30.bred 50:06:0B:00:00:C2:62:1D PRD-VM16 50:06:0B:00:00:C2:62:1F PRD-VM16 50:06:0B:00:00:C3:4E:1D prd-vm07 50:06:0B:00:00:C3:4E:1F prd-vm07
我想输出应该如下所述:
fc1/16 20:B0:00:25:B5:FF:11:0D prd-vm32 fc1/17 20:B0:00:25:B5:FF:11:0B prd-vm30.bred
请告诉我,我怎样才能达到同样目的。
答案 0 :(得分:0)
join(1)
遭受排序必要性问题;将密钥存入哈希可以避免这种情况(以更大的内存使用为代价)。
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my %by_mac;
my ($file1, $file2) = @ARGV; # TODO usage notes if not set
open my $f1, '<', $file1; # TODO error checking on open
open my $f2, '<', $file2; # TODO error checking on open
while (my $line = readline $f1) {
chomp $line;
my @col = split ' ', $line;
$by_mac{ lc $col[1] }->[0] = $col[0];
}
while (my $line = readline $f2) {
chomp $line;
my @col = split ' ', $line;
$by_mac{ lc $col[0] }->[1] = $col[1];
}
#use Data::Dumper; print Dumper \%by_mac;
for my $key (keys %by_mac) {
if ( grep(defined, @{ $by_mac{$key} }) == 2 ) {
say join " ", $by_mac{$key}->[0], $key, $by_mac{$key}->[1];
}
}
答案 1 :(得分:0)
awk 'FNR==NR{arr[toupper($2)]=$1;next}
($1 in arr){print arr[$1],$0;delete arr[$1]}' file1 file2
FNR:当前文件中当前记录的序号。
NR:从输入开始的当前记录的序号。
next:跳过行处理并继续下一行。
在阅读第一行时,FNR = NR。将第一列($ 1)存储到数组arr中,索引大写第二个字段($ 2)并跳到下一行。
在处理第二个文件时,循环遍历数组元素。 如果第二个文件的$ 1是数组元素,则从第二个文件中打印数组值和行。删除数组元素以跳过重复项。