Reputation: 346
The logic I'd like to write is as follows:
From File 1, compare column 1 and also compare column 3 against any row in column 1 of File 2. If a match is made, print the line from File 1, along with column 2's values (2) from File 2, as two new columns.
When performing the match, only match the first 5 characters.
File 1: Node Links
NODE1 eth1 NODE2 eth1
NODE1 eth2 NODE3 eth1
NODE2 eth2 NODE4 eth1
NODE3 eth2 NODE4 eth2
File 2: Node Loopbacks
NODE1-USA 10.0.0.1/32
NODE2-USA 10.0.0.2/32
NODE3-USA 10.0.0.3/32
NODE4-USA 10.0.0.4/32
Output File:
NODE1 10.0.0.1/32 eth1 NODE2 10.0.0.2/32 eth1
NODE1 10.0.0.1/32 eth2 NODE3 10.0.0.3/32 eth1
NODE2 10.0.0.2/32 eth2 NODE4 10.0.0.4/32 eth1
NODE3 10.0.0.3/32 eth2 NODE4 10.0.0.4/32 eth2
Here's the basics of what I want but with an additional match.
awk 'FNR==NR{a[$1]=$2;next}{print $0,a[$1]?a[$1]:"NA"}' file2 file1
Upvotes: 0
Views: 1458
Reputation: 67557
awk
to the rescue!
$ awk 'NR==FNR {a[substr($1,1,5)]=$2; next}
{print $1,a[$1],$2,$3,a[$3],$4}' file2 file1
NODE1 10.0.0.1/32 eth1 NODE2 10.0.0.2/32 eth1
NODE1 10.0.0.1/32 eth2 NODE3 10.0.0.3/32 eth1
NODE2 10.0.0.2/32 eth2 NODE4 10.0.0.4/32 eth1
NODE3 10.0.0.3/32 eth2 NODE4 10.0.0.4/32 eth2
please note the order of the files
If there are unmatched entries you want to decode to "NA" instead of empty string, change a[$1]
to ($1 in a)?a[$1]:"NA"
, similarly for a[$3]
.
Upvotes: 1