user3595099 user3595099 - 1 month ago 5
Linux Question

script for checking IP's hostname from file

I used for to file one contain the IP with hostname like the /ec/hosts
and the other contain the IP and counter try to print the ip if hostname not found and if is found print the hostname.

Script:

for i in `cat ip | awk '{print $2}'` ;do
var=`grep "$i" Server_ip` |
awk ' {if($var == "") print $i else print $1}';
done


File 1

localhost 127.0.0.1
test 10.0.0.1
test1 10.0.0.2


File 2

3 127.0.0.1
2 10.0.0.1
1 10.0.0.2
4 10.0.0.3
5 10.0.0.4


Desired output

localhost
test
test1
10.0.0.3
10.0.0.4

Answer

You can try this;

#!/bin/bash
for i in `cat ip | awk '{print $2}'` ;do
var=`awk -v ip=${i} '$2 == ip {print $1}' Server_ip`

 if [ -z "$var" ]; then
  echo $i
 else 
  echo "$var"
 fi

done

Eg;

user@host:/tmp/test$ cat Server_ip
localhost 127.0.0.1
test 10.0.0.1
test1 10.0.0.2

user@host:/tmp/test$ cat ip
3 127.0.0.1
2 10.0.0.1
1 10.0.0.2
4 10.0.0.3
5 10.0.0.4

user@host:/tmp/test$ ./test.sh
localhost
test
test1
10.0.0.3
10.0.0.4
Comments