Text Processing – How to Join Two Files Using a Shell Script

awkjoin;text processing

I want to write a shell script that get two files A and B, and get a result like this:

File A:

user_a tel_a addr_a
user_b tel_b addr_b

File B:

process_1 user_a
process_2 user_a
process_3 user_b

And the result:

user_a process_1 tel_a addr_a
user_a process_2 tel_a addr_a
user_b process_3 tel_b addr_b

How can i do this? awk or something else?

Best Answer

join ...

join -1 2 -2 1 FileB FileA

Output

user_a process_1 tel_a addr_a
user_a process_2 tel_a addr_a
user_b process_3 tel_b addr_b

The input files need to be sorted by the key field ... Your example files are already sorted, so there was no need, but otherwise you could incorporate the sort as follows.

join -1 2 -2 1 <(sort -k2 FileB) <(sort FileA)
Related Question