Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ubuntu - joining two files based on first column IDs

I have two files, with the pattern

file1 (smaller file)

001 word1
002 word2
... ....
00n wordn

file2 (bigger file)

001 word3
002 word4
... ....
00n wordn

I want to get an output file that keeps only matching lines from both files, based on the first column of file1 and joins the two lines where it finds a common column ID, such as, for example

001 001 word1 word 3

Tried various comobos of join, grep and awk but the task seems to be beyond me.

Many thanks!

question from:https://stackoverflow.com/questions/65829613/joining-two-files-based-on-first-column-ids

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given:

$ cat file1
001 word1
002 word2
00n wordn1

$ cat file2 
001 word3
002 word4
003 word_u1
004 word_u2
00n wordn2

(Note the extra 003 word_u1 and 004 word_u2 in file2...)

You can use join that joins those files (as presented) together:

$ join file1 file2
001 word1 word3
002 word2 word4
00n wordn1 wordn2

If the files are not sorted (as you have presented them) you can sort first:

$ join <(sort file1) <(sort file2)

If you want to double up the digits, pipe to sed:

$ join file1 file2 | sed -nE 's/^([^[:space:]]*)/1 1/p'
001 001 word1 word3
002 002 word2 word4
00n 00n wordn1 wordn2

Or specify the join output list:

$ join -o 1.1,2.1,1.2,2.2 file1 file2
001 001 word1 word3
002 002 word2 word4
00n 00n wordn1 wordn2    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...