Linux join Command: File Joining

LinuxLinuxBeginner
Practice Now

Introduction

This tutorial provides an introduction to the join command in Linux, a utility that merges lines from two sorted text files based on a common field.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux/TextProcessingGroup -.-> linux/join("`File Joining`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") subgraph Lab Skills linux/join -.-> lab-219193{{"`Linux join Command: File Joining`"}} linux/cd -.-> lab-219193{{"`Linux join Command: File Joining`"}} end

join Command

The join command is a helpful tool for combining lines from two sorted files where specified fields match, providing a powerful way to merge information from multiple sources.

Command Usage

Let's begin by understanding the basic usage of the join command. The join command merges lines from two sorted files based on a common field. And first, by using cd /home/labex/project, we change to the specified path /home/labex/project.

terminal

Input:

cd /home/labex/project
join file1.txt file2.txt

Output:

webb 2000 2 php 3
zark 2600 2 java 2
zoey 2000 1 c 1

In this example, the join command merges lines from file1.txt and file2.txt based on the common field (the first column).

Parameters and Usage Examples

The join command provides options to customize the output and specify the fields for joining.

Option Parameter

join [option] file1 file2

  • -1 FIELD: Match with FIELD field in file1.
  • -2 FIELD: Match with FIELD field in file2.
  • -a : Include unpairable lines from file1 or file2.
  • -v : Select lines that do not have a match.

Example Usage

1. Specify Fields for Joining

The join command can be configured to join lines based on specific fields. In this example, we join lines from file3.txt and file4.txt based on the third column:

Input:

join -1 3 -2 3 file3.txt file4.txt

Output:

2 lisa 2500 zark java
2 webb 2000 zark java
2 zark 2600 zark java

2. Display Unpairable Lines

You can use the join command to display unpairable lines from either file. In this example, we display lines from file1.txt that do not have a match in file2.txt:

Input:

join -a 1 -v 1 file1.txt file2.txt

Output:

lisa 2500 2

Summary

The join command is a valuable tool for merging lines from two sorted files based on common fields. Whether you need to specify fields for joining, display unpairable lines, or customize the output format, the join command provides flexibility for combining information from multiple sources.

Other Linux Tutorials you may like