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


file B

1 kfjk 3243424
2 fkdkf 23543592
3 iefjk 21493402
7 dlafdl 23435231
8 kfkdlkf 309834
  • 2
    Better provide sample input & output. – Gilles Quenot Nov 16 '12 at 11:42

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.)

  • 1
    Process substitution (join <(sort A) <(sort B)) works just fine in bash :-) – Will Vousden Mar 10 '16 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.