Reputation: 3
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
Upvotes: 0
Views: 548
Reputation: 67467
this is the standard use case for join
, for files are in sorted order already. No need to any additional code.
$ join file1 file2
A10 Unix RedHat
B20 Security Loadbalancing
Upvotes: 2
Reputation: 203209
$ awk 'NR==FNR{a[$1]=$2;next} $1 in a{print $0, a[$1]}' file2 file1
A10 Unix RedHat
B20 Security Loadbalancing
Upvotes: 1
Reputation: 157947
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
}
Upvotes: 0