开发者

Compare Txt Files in Linux and Return Elements in File 1 for Elements in File 2

开发者 https://www.devze.com 2023-03-06 03:36 出处:网络
Here is the problem. Host.txt file has only Hostnames as follows: GVC-CH-ZRH-BRA-5H81-PELE GVC-US-NYC-9TH-4C101-MEDROOM

Here is the problem.

  1. Host.txt file has only Hostnames as follows:
GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

  1. IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:
170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please He开发者_运维知识库lp!


sort Host.txt -o Host_sorted.txt
sort HosandIp.txt -o HosandIp_sorted.txt
join Host_sorted.txt HosandIp_sorted.txt -t, | cut -d, -f2

The input files must be sorted. The entries aren't quite sorted in the order desired by join, therefore I've included the calls to sort to do this. Join man page


Here is my 0.02$ in perl

#!/usr/bin/perl
use strict;
use warnings;

open (HOST, '<Host.txt') || die;
open (HOSTANDIP, '<HostAndIp.txt') || die;

my %host2ip;
map { chomp; my ($h,$i) = split /,/; $host2ip{$h} = $i } (<HOSTANDIP>);

map { chomp; print "$host2ip{$_}\n" if exists($host2ip{$_}) } (<HOST>);


awk -F, '
  NR == FNR {host[$1]++; next}
  ($1 in host) {print $2}
' Host.txt HostandIP.txt > IPOnly.txt


My take using Python:

hosts_contents = open('Host.txt', 'r').read()
hosts_and_ips_contents = open('HosandIp.txt', 'r').read()
host_ips = dict(line.split(',') for line in hosts_and_ips_contents.splitlines())
hosts_wanted = set(hosts_contents.splitlines())
print '\n'.join(ip for host, ip in host_ips.iteritems() if host in hosts_wanted)


sed -e 's/^/\^/' -e 's/$/,/' Host.txt | egrep -f - HosandIp.txt | awk -F, '{print $2}' > IPOnly.txt


one-liner:

for line in $(cat host.txt); do sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt ; done > ip-only.txt

in readable form:

for line in $(cat host.txt)
do
  sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt 
done > ipOnly.txt
0

精彩评论

暂无评论...
验证码 换一张
取 消