awk匹配两个文件并打印所需的输出

时间:2018-02-28 20:12:24

标签: awk multiple-columns rows

awk gurus,我在这里尝试了很多awk提示,但是无法用所需的输出来解决这个问题我试图得到将近4天的时间,也许我在以下类似的awk中找不到解决这个难题的东西查询,但没有成功。

尝试以下变体:

 awk 'NR==FNR{a[$1]=$5;print;next}{for(i in a)if(a[i]==$1)print $2,i}'
 awk -F '[| ]+' -v OFS='\t' 'NR==FNR{a[$4]=$1 OFS $2; next}
       $1 in a{print $1, a[$1]}' file2 file1

awk 'NR==FNR{a[$0]=1;next} {n=0;for(i in a){if(substr($0,22,3)~i) { n=1}  } } n' file2 file

INPUT FILE1匹配:

T ASDasd  2 AAAAA BBBBB Device 
T as9df7  2 CCCCC QQQQQ Device 
T a987fa  3 EEEEE FFFFF Device 
T asd4f6  3 88888 TTTTT Device
T 56sd4f  3 HHHHH SSSSS Device
T 56sd4f  3 00000 UUUUU Device
T 56sd4f  3 77777 45454 Device

INPUT FILE2用于与FILE1匹配:

AAAAA INFO CAR
XXXXX INFO CAR
CCCCC INFO TRUCK
DDDDD INFO TRUCK
GGGGG INFO TRAIN
TTTTT INFO TRAIN
RRRRR INFO BMW
SSSSS INFO VOLVO
WWWWW INFO VOLVO
EEEEE INFO SYS
PPPPP INFO SYS
00000 INFO RIVER
77777 INFO RIVER

OUTPUT应为:

T ASDasd  2 AAAAA INFO CAR Device
T as9df7  2 CCCCC INFO TRUCK Device
T a987fa  3 EEEEE INFO SYS Device
T asd4f6  3 TTTTT INFO TRAIN Device
T 56sd4f  3 SSSSS INFO VOLVO Device
T 56sd4f  3 00000 INFO RIVER Device
T 56sd4f  3 77777 INFO RIVER Device

它将file2(第1列)与file1(第4 + 5列)进行匹配,并与具有任何匹配数据的名称的打印输出进行比较。

我对此非常感兴趣,仍在学习awk以了解如何为此编写awk查询。祝大家度过美好的一天。

tried this but its resulting to its not fully desired output ad not sure where to look exactly and why its otputting file2 with result info

 awk 'NR==FNR{a[$1]=$3;print;next}{for(i in a)if(a[i]==$8)print $1 " " $2 " " $3 " " $4 ,i}' match2 match1
AAAAA INFO CAR
XXXXX INFO CAR
CCCCC INFO TRUCK
DDDDD INFO TRUCK
GGGGG INFO TRAIN
TTTTT INFO TRAIN
RRRRR INFO BMW
SSSSS INFO VOLVO
WWWWW INFO VOLVO
EEEEE INFO SYS
PPPPP INFO SYS
00000 INFO RIVER
77777 INFO RIVER




T ASDasd 2 AAAAA
T as9df7 2 CCCCC
T a987fa 3 EEEEE
T asd4f6 3 88888
T 56sd4f 3 HHHHH
T 56sd4f 3 00000
T 56sd4f 3 77777

1 个答案:

答案 0 :(得分:0)

awk救援!

$ awk 'NR==FNR {a[$1]=$2 FS $3; next} 
               {if($4 in a) $5=a[$4]; 
                else if($5 in a) {$4=$5; $5=a[$5]}}1' file2 file1

T ASDasd 2 AAAAA INFO CAR Device
T as9df7 2 CCCCC INFO TRUCK Device
T a987fa 3 EEEEE INFO SYS Device
T asd4f6 3 TTTTT INFO TRAIN Device
T 56sd4f 3 SSSSS INFO VOLVO Device
T 56sd4f 3 00000 INFO RIVER Device
T 56sd4f 3 77777 INFO RIVER Device