Enhancing Skills

join: Join lines of two files on a common field

The join command is used to merge lines of two files based on a common field. It is commonly used for combining data from two files with a shared key or column.

Command:

join [options] file1 file2
Copy

001join [options] file1 file2

Examples

  1. Join Two Files on the First Field
   join file1.txt file2.txt
Copy

001 join file1.txt file2.txt

Sample File (file1.txt):

   1 Alice
   2 Bob
   3 Charlie
Copy

001 1 Alice

002 2 Bob

003 3 Charlie

Sample File (file2.txt):

   1 Engineer
   2 Designer
   3 Manager
Copy

001 1 Engineer

002 2 Designer

003 3 Manager

Sample Output:

   1 Alice Engineer
   2 Bob Designer
   3 Charlie Manager
Copy

001 1 Alice Engineer

002 2 Bob Designer

003 3 Charlie Manager

  1. Join on a Specific Field and Use a Custom Delimiter
   join -t ',' -1 2 -2 1 file1.csv file2.csv
Copy

001 join -t ',' -1 2 -2 1 file1.csv file2.csv

Sample File (file1.csv):

   Name,1
   Bob,2
   Charlie,3
Copy

001 Name,1

002 Bob,2

003 Charlie,3

Sample File (file2.csv):

   1,Engineer
   2,Designer
   3,Manager
Copy

001 1,Engineer

002 2,Designer

003 3,Manager

Sample Output:

   Bob,2,Designer
   Charlie,3,Manager
Copy

001 Bob,2,Designer

002 Charlie,3,Manager

  1. Print Unmatched Lines from Each File
   join -v 1 file1.txt file2.txt
Copy

001 join -v 1 file1.txt file2.txt

Sample File (file1.txt):

   1 Alice
   2 Bob
   4 Dave
Copy

001 1 Alice

002 2 Bob

003 4 Dave

Sample File (file2.txt):

   1 Engineer
   2 Designer
   3 Manager
Copy

001 1 Engineer

002 2 Designer

003 3 Manager

Sample Output:

   4 Dave
Copy

001 4 Dave

  1. Join Files Using a Different Field
   join -1 2 -2 1 file1.txt file2.txt
Copy

001 join -1 2 -2 1 file1.txt file2.txt

Sample File (file1.txt):

   Alice 1
   Bob 2
   Charlie 3
Copy

001 Alice 1

002 Bob 2

003 Charlie 3

Sample File (file2.txt):

   Engineer 1
   Designer 2
   Manager 3
Copy

001 Engineer 1

002 Designer 2

003 Manager 3

Sample Output:

   Alice 1 Engineer
   Bob 2 Designer
   Charlie 3 Manager
Copy

001 Alice 1 Engineer

002 Bob 2 Designer

003 Charlie 3 Manager


The join command is effective for combining data based on a shared key or column, making it useful for various data processing tasks.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.