intersection of two files according to the first column

I have two files
in file A, there are sequence_numbers
in the other file B, there are many columns, and the first column is sequnce numbers,
I want to get a files with all the lines in the B with the sequence numbers which are in the A
how can I achieve this?
thanks

like
file A

1
3
8
9
20

file B

1 kfjk 3243424
2 fkdkf 23543592
3 iefjk 21493402
7 dlafdl 23435231
8 kfkdlkf 309834

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You want join (1), I guess:

For each pair of input lines with identical join fields, write a
line
to standard output. The default join field is the first, delimited by
whitespace. When FILE1 or FILE2 (not both) is -, read standard input.

[0 1075 12:50:10] ~/temp/sx % join A B
1 kfjk 3243424
3 iefjk 21493402
8 kfkdlkf 309834
join: file 1 is not in sorted order

OK, so apparently you need to combine this with sort (1) to sort by alpha value (not numerical value, so 20 < 3)

join <(sort A) <(sort B) works for me, but that looks weird and might be a zsh extension. There’s no harm in doing

sort A > A.tmp; sort B > B.tmp; join A.tmp B.tmp

(As usual, check the man pages for pitfalls.)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x