Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Matching colums from two files

Status
Not open for further replies.

kHz

MIS
Dec 6, 2004
1,359
US
I have a file (A) that contains:

Host1
bge0: xx.xxx.xx.xxx
bge1: xx.xxx.xx.xxx

Host2
bge0: xx.xxx.xx.xx
bge1: xx.xxx.xx.xx
.
.
.

Another file (B) contains:
Host1-db xx.xxx.xx.xxx
Host2-nbu xx.xxx.xx.xxx
Host1-app xx.xxx.xx.xxx

What I want to do is if the IP in file (B) in column 2 matches an IP in file (A) then print column 1 from file B next to the IP in file A.

For example:
Host1
bge0: xx.xxx.xx.xxx Host1-db
bge1: xx.xxx.xx.xxx Host1-app

Host2
bge0: xx.xxx.xx.xx Host2-app
bge1: xx.xxx.xx.xx Host2-nbu
.
.
.


Thanks!
 
read FileB in as an associative array indexed by column2 (with the value of column1) AND do the lookup as you process data from FileA.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
A starting point:
awk '
FNR==NR{t[$2]=$1;next}
{print $0,t[$2]}
' /path/to/fileB /path/to/fileA > output

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
vlad said:
read FileB in as an associative array indexed by column2 (with the value of column1) AND do the lookup as you process data from FileA.
This is what PHV did. With comments:
[tt]
# NR holds the total number of records (lines) read.
# FNR holds the number of records read from current
# file. When they're equal, we're still in the 1st file.
FNR==NR {
t[$2]=$1
# Skip rest of code; read next line immediately.
next }
# We're in the second file. Print line just read
# followed by info from file 1.
{ print $0, t[$2] }
[/tt]
For an introduction to Awk, see FAQ271-5564.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top