简体   繁体   中英

Print common line from two files - Bash

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

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
$ awk 'NR==FNR{a[$1]=$2;next} $1 in a{print $0, a[$1]}' file2 file1
A10 Unix RedHat
B20 Security Loadbalancing

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
}

i want to get common word from two different files in bash

Not a line but common word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM