文件1是/etc/hosts
文件,输出低于
10.0.0.1 router1
10.0.0.2 router2
10.0.0.3 router3
10.0.0.4 router4
在/usr/local/rancid/var/devices/router.db
中将两个id作为一个rancid数据库,输出如下:
router1:cisco:up
router2:cisco:up
我希望能够运行一个只能查找主机名routerx
的脚本,并找到哪些尚未添加到router.bd
routerx:cisco:up
的主机名。
所以我在上面的例子中寻找的输出是:
打印缺少路由器
router3
router4
端
你能帮忙解决一些问题或指出我正确的方向吗?
答案 0 :(得分:2)
你可以使用这个awk:
awk -F '[: ]+' 'FNR==NR {a[$1]; next} !($NF in a) {print $NF}' router.db hosts
router3
router4
<强>解释强>
-F '[: ]+' # Use custom field separator as 1 or more of colon or space
FNR==NR # for first file populate an array `a` with key as $1
next # keep reading 1st file till EOF is reached
!($NF in a) # from 2nd file execute {...} if last fieild in NOT in array a
{print $NF} # print last field from hosts file
答案 1 :(得分:1)
尝试:
routerdb="/usr/local/rancid/var/devices/router.db"
while read _ router; do
grep -q "^$router:" $routerdb || echo "Missing: $router"
done < /etc/hosts
答案 2 :(得分:0)
您可以通过以下方式完成: -
awk -F'\t' {'print $2'} /etc/hosts > temp.txt
awk -F':' {'print $2'} /usr/local/rancid/var/devices/router.db > temp1.txt
cat temp.txt | while read a
do
i=`grep -c $a temp1.txt`
if [ $i -eq 0 ]
then
echo $a
fi
done
这将打印路由器3&amp;路由器4 ..
答案 3 :(得分:-1)
diff
通常是一个不错的选择。完整的解决方案可能如下所示:
#!/bin/bash
ROUTERDB=/usr/local/rancid/var/devices/router.db
HOSTS=/etc/hosts
# use a temporary directory:
DIR=$(mktemp -d)
cd ${DIR}
# write first field of router.db in one file, using : as delimiter:
awk -F: '{ print $1 }' ${ROUTERDB} > routerdb
# write second field of hosts in the other:
awk '{ print $2 }' ${HOSTS} > hosts
# compare the two files, select only lines not in
# router.db, and remove the + sign at the beginning:
echo Missing routers
diff -u routerdb hosts | grep "^+[^+]" | tr -d "+"
echo end
# remove temporary directory:
rm -rf ${DIR}