user3834663
user3834663

Reputation: 543

Compare two files using awk and print the matched lines

I have two files got following information. i need to compare bothe the files and print lines matched in FILE2.

FILE1.txt

martin01
kevin01
phoenix01
samson01
edward01

FILE2.txt

martin01.test.com empid: 9874712
martin01.test1.com empid:0972292
kevin01.test.com empid: 3297203
kevin01.test.com empid: 3297203
phoenix01.test.com empid: 9872219
phoenix01.test1.com empid:9803994
samson01.test.com empid: 0983903
samson01 empid: 7665758
edward01.test.com empid: 0979072
edward01.test2.com empid: 748840
gregory01.test.com empid: 657758
clevin01.test.com empid:6589598

Expected output should be like this:

martin01.test.com empid: 9874712
martin01.test1.com empid:0972292
kevin01.test.com empid: 3297203
kevin01.test.com empid: 3297203
phoenix01.test.com empid: 9872219
phoenix01.test1.com empid:9803994
samson01.test.com empid: 0983903
samson01 empid: 7665758
edward01.test.com empid: 0979072
edward01 empid: 748840

This is what i wrote but somewhere its wrong..

awk 'FNR==NR {a[$1]; next} $1 in a' FILE1.txt FILE2.txt

Upvotes: 0

Views: 923

Answers (2)

Ed Morton
Ed Morton

Reputation: 203169

you need to set the FS to .:

awk -F'[.[:space:]]' 'FNR==NR {a[$1]; next} $1 in a' FILE1.txt FILE2.txt

Upvotes: 2

karakfa
karakfa

Reputation: 67467

alternative to awk

$ grep -Ff file1 file2

martin01.test.com empid: 9874712
martin01.test1.com empid:0972292
kevin01.test.com empid: 3297203
kevin01.test.com empid: 3297203
phoenix01.test.com empid: 9872219
phoenix01.test1.com empid:9803994
samson01.test.com empid: 0983903
samson01 empid: 7665758
edward01.test.com empid: 0979072
edward01.test2.com empid: 748840

note that the match is anywhere in the line, not confined to first field only. Use this if your fields are disjoint sets.

Upvotes: 2

Related Questions