join: Join lines of two files on a common field
August 12th, 2024 12:43 PM Mr. Q Categories: Command
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
Examples
- Join Two Files on the First Field
join file1.txt file2.txt
Sample File (file1.txt
):
1 Alice
2 Bob
3 Charlie
Sample File (file2.txt
):
1 Engineer
2 Designer
3 Manager
Sample Output:
1 Alice Engineer
2 Bob Designer
3 Charlie Manager
- Join on a Specific Field and Use a Custom Delimiter
join -t ',' -1 2 -2 1 file1.csv file2.csv
Sample File (file1.csv
):
Name,1
Bob,2
Charlie,3
Sample File (file2.csv
):
1,Engineer
2,Designer
3,Manager
Sample Output:
Bob,2,Designer
Charlie,3,Manager
- Print Unmatched Lines from Each File
join -v 1 file1.txt file2.txt
Sample File (file1.txt
):
1 Alice
2 Bob
4 Dave
Sample File (file2.txt
):
1 Engineer
2 Designer
3 Manager
Sample Output:
4 Dave
- Join Files Using a Different Field
join -1 2 -2 1 file1.txt file2.txt
Sample File (file1.txt
):
Alice 1
Bob 2
Charlie 3
Sample File (file2.txt
):
Engineer 1
Designer 2
Manager 3
Sample Output:
Alice 1 Engineer
Bob 2 Designer
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.