Use awk to compare two files based on one column

时间:2018-04-18 18:12:24

标签: linux awk

I have two files which look like this:

file 1:

abc 123
def 456
ghi 789

file 2:

abc 321
ghi 987

I've heard awk is what I need, but how can I use it to make this desired output?

abc 321
def 456
ghi 987

You can assume all data has been de-duplicated within the files. So the only thing it needs to do is iterate through the files, and if there's a match between files 1 and 2 on column 1, the output should be the information in file 2.

Thanks in advance!

2 个答案:

答案 0 :(得分:1)

使用GNU排序:

sort -k1,1 -u file2 file1

输出:

abc 321
def 456
ghi 987

答案 1 :(得分:0)

假设file2中的键严格地是file1

中出现的键的子集
awk 'NR==FNR {f2[$1] = $2; next} $1 in f2 {$2 = f2[$1]} 1' file2 file1