user3595099 user3595099 - 3 months ago 5
Linux Question

Merging and comparing files using Linux command

I have a question about merging 2 data files. The first file contains an IP address for the name of each server. The second contains a data item and the associated IP address.

For output, I'd like to have the input of the second file, but with the mapped server name, looked up in the first file.

File_1:

10.1.1.1 server_1
10.1.1.2 server_2
10.1.1.3 server_3


File_2:

2 10.1.1.3
4 10.1.1.1


I need to figure out a command for getting the output below:

Output_file:

2 10.1.1.3 server_3
4 10.1.1.1 server_1

Answer

You can use awk:

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

2  10.1.1.3 server_3
4  10.1.1.1 server_1