Reputation: 3162
I have two files: one contains a list of AP names, and another list contains AP names again, but this time the controller IP for each AP is listed before the AP's name.
File 1:
AP1
AP2
Ap3
AP4
Ap5
Ap6
...
File 2:
1.1.1.1,Ap1
2.2.2.2,Ap2
3.3.3.3,Ap3
4.4.4.4,Ap4
6.6.6.6,Ap6
...
How can I match up the names from file 1 with the names in file 2 so that the output resembles the following?
1.1.1.1,Ap1
2.2.2.2,Ap2
3.3.3.3,Ap3
4.4.4.4,Ap4
IP Not Found,Ap5
6.6.6.6,Ap6
I was thinking that I could use the comm
command, but I do not know of a good way to only compare the names and not the IPs. I could also just grep for every single name, but that would take forever (there are around 8,000 AP names).
Upvotes: 0
Views: 86
Reputation: 239861
The join
command will do the job (note that both files have to be sorted by AP name first; your example data already is, but if your real-world data isn't, run the first file through sort -f
, and the second file through sort -f -t , -k 2
).
join -i -t , -1 1 -2 2 -a 1 -o 2.1,1.1 -e "IP Not Found" file1.txt file2.txt
-i
means ignore case, -t ,
means fields are separated by commas, -1 1
means join on the first (only) field of the first file; -2 2
means join on the second field of the second file. -a 1
means include rows from the first file that don't have any matches. -o 2.1,1.1
specifies the output format: the first field of the second file (IP), then the first field of the first file (AP). -e "IP Not Found"
means to output "IP Not Found" in place of an empty field.
This will output
1.1.1.1,AP1
2.2.2.2,AP2
3.3.3.3,Ap3
4.4.4.4,AP4
IP Not Found,Ap5
6.6.6.6,Ap6
Upvotes: 3
Reputation: 36096
This awk snippet should do it:
awk 'BEGIN{FS=","}
(FNR==NR){a[tolower($2)]=$0}
(FNR!=NR){if (a[tolower($1)]!="")
print a[tolower($1)]
else
print "IP Not Found," $1}' file2.txt file1.txt
producing in your case:
1.1.1.1,Ap1
2.2.2.2,Ap2
3.3.3.3,Ap3
4.4.4.4,Ap4
IP Not Found,Ap5
6.6.6.6,Ap6
Upvotes: 1