Johnny B
Johnny B

Reputation: 31

Awk: How do I output data from two files

So yeah im trying to match file1 that contains email to file2 that cointains email colons address, how do i go on bout doing that?

tried awk 'FNR==NR{a[$1]=$0; next}{print a[$1] $0}' but idk what im doing wrong

file1:

[email protected]
[email protected]
[email protected]

file2:

[email protected]:addressotest
[email protected]:clubbingson
[email protected]:addresso2

output:

[email protected]:addresso2
[email protected]:addressotest

Upvotes: 2

Views: 76

Answers (3)

karakfa
karakfa

Reputation: 67507

join with presorting input files

$ join -t: <(sort file1) <(sort file2)

[email protected]:addressotest
[email protected]:addresso2

Upvotes: 1

Allan
Allan

Reputation: 12438

Hey why going for a awk solution when you can simply use the following join command:

join -t':' file 1 file2

where join as its names indicate is just a file joining command and you chose the field separator and usually the input columns and output to display (here not necessary)

Tested:

$more file{1,2}
::::::::::::::
file1
::::::::::::::
[email protected]
[email protected]
[email protected]
::::::::::::::
file2
::::::::::::::
[email protected]:addressotest
[email protected]:clubbingson
[email protected]:addresso2

$join -t':' file1 file2
[email protected]:addressotest
[email protected]:addresso2

If you need to sort the output as well, change the command into:

join -t':' file 1 file2 | sort -t":" -k1 

or

join -t':' file 1 file2 | sort -t":" -k2

depending on which column you want to sort upon (eventually add the -r option to sort in reverse order.

join -t':' file 1 file2 | sort -t":" -k1 -r

or

join -t':' file 1 file2 | sort -t":" -k2 -r

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133528

Following awk may help you in same.

awk 'FNR==NR{a[$0];next} ($1 in a)' FILE_1 FS=":" FILE_2

Upvotes: 1

Related Questions