首页 > 解决方案 > compare different column of 2 different files and keep the orderin awk script

问题描述

I am trying to compare 2 different files ex:

file 1:

CALL AA
CALL AB
CALL AC

file 2:

00 AB n
01 AA o
02 AC o

the result i expect is output:

AA 01 o
AB 00 n
AC 02 o

How can i get this without changing the order of the first file?(preferably in awk) Thank you in advance.

标签: awk

解决方案


从上面链接的示例更改

awk 'NR==FNR {x=$1; $1="";a[x]=$0; next} {print $0,a[$3]}' Sourceports NATLog

awk 'NR==FNR {x=$2; $2="";a[x]=$0; next} {print $2,a[$2]}' file2 file1

输出:

AA 01 o
AB 00 n
交流电 02 o

通过优化:

awk 'NR==FNR {a[$2]=$2 FS $1 FS $3; next} {print a[$2]}' file2 file1

现在输出没有空列:

AA 01 o
AB 00 n
交流电 02 o

请参阅:8 个强大的 Awk 内置变量——FS、OFS、RS、ORS、NR、NF、FILENAME、FNR


推荐阅读