Tuesday, October 4, 2022

[SOLVED] Print common line from two files - Bash

Issue

I have two files and I'd like to find common 1st column on each lines and print 1st & 2nd column of file1.txt and 2 column of file2.txt.

file1.txt
A10 Unix
A20 Windows
B10 Network
B20 Security

file2.txt
A10 RedHat
A21 Win2008
B11 Cisco
B20 Loadbalancing

Result:

file.txt
A10 Unix RedHat
B20 Security Loadbalancing

I tried code below but doesn't retrive correct result:

$ awk 'NR==FNR {a[$1]=$1; next} $1 in a {print a[$1], $0}' file1.txt file2.txt

Solution

You can use the following awk command:

awk 'NR==FNR{a[$1]=$2} NR>FNR && $1 in a{print $1,a[$1],$2}' file1.txt file2.txt

Better explained in a multiline version:

# Number of record is equal to number of record in file.
# True as long as we are reading file1
NR==FNR {
    # Stored $2 in an assoc array index with $1
    a[$1]=$2
}

# Once we are reading file2 and $1 exists in array a
NR>FNR && $1 in a {
    # print the columns of interest
    print $1, a[$1], $2
}


Answered By - hek2mgl
Answer Checked By - Mildred Charles (WPSolving Admin)