AWK joining two files on a specific column

旧巷老猫 提交于 2019-12-22 12:40:24

问题


I'm trying to join two files on one of their columns and the output should be the columns of the second file and some of the columns from the first file.

For example my first file is:

subscriberid unsubscribetime unsubscribeip listid statid unsubscribed

and my second file is:

listid statid listname ownername owneremail createdate subscriberid bouncetype bouncetime bouncerule

I need to join them on the "statid" column which is 5th in the first file and 2nd in the second file. After that add 2nd, 3rd and 6th column from the first file. The output should be:

listid statid listname ownername owneremail createdate subscriberid bouncetype bouncetime bouncerule unsubscribetime unsubscribeip unsubscribed

I am having trouble understanding the syntax, but I was using this command:

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

I thought it would give me the file2 columns, because of "print $0" and the second column form file one which is set to a[$5]=$2, but it only outputs the file2 columns.

Where am I making a mistake, please? How to join the 2nd, 3rd and 6th column from file1 to file2?

Any help/explanations are very much appreciated!

both files in this example have only one row


回答1:


I'm sure if you see this and think about it a bit you'll figure it out:

$ awk 'NR==FNR{a[$5]=$2" "$3" "$6;next} $2 in a{print $0, a[$2]}' file1 file2
listid statid listname ownername owneremail createdate subscriberid bouncetype bouncetime bouncerule unsubscribetime unsubscribeip unsubscribed


来源:https://stackoverflow.com/questions/17342954/awk-joining-two-files-on-a-specific-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!