使用 bash 监控文件的变化

使用 bash 监控文件的变化

我在本地网络上运行 DHCP 服务器,它每隔几秒钟调用一次此脚本:

dumpleases | awk '{print $2}' > leasesnow     #get list of all IPs leased in a file, one per line
ADDED=`awk 'NR==FNR{a[$1]=$2;next} !($1 in a) { print $2 }' leasesthen leasesnow`     #try to extract only new leases to variable
print $ADDED
checkin.sh $ADDED    #do something with new devices on network
cp -f leasesnow leasesthen

我也尝试过使用 diff,但它看起来比 awk 更复杂,因为它需要先从输出中过滤掉更改的行。

错误之处:$ADDED 从未收到正确的值(甚至任何值),这意味着 awk 无法按预期工作。您能解释一下错误之处吗?我对 awk 还很陌生。谢谢。

答案1

我知道您正在寻找的工具!comm

当前 ips 文件old.txt

68.180.194.242
68.180.194.243
69.147.112.168
69.147.112.169
87.248.122.141
87.248.122.142
209.131.41.48
209.131.41.49
216.39.58.17
216.39.58.18
216.39.58.78
217.12.1.124
217.12.1.125
217.146.191.18
217.146.191.19
87.248.125.48
87.248.125.49
98.136.63.35

新的 ips 文件new.txt

68.180.194.242
68.180.194.243
69.147.112.168
69.147.112.169
87.248.122.141
87.248.122.142
209.131.41.48
209.131.41.49
216.39.58.17
216.39.58.18
216.39.58.78
217.12.1.124
217.12.1.125
217.146.191.18
217.146.191.19
87.248.125.48
87.248.125.49
98.136.63.35
68.142.243.103
98.139.134.96
98.139.134.97
98.139.134.98
98.139.134.99
173.224.120.84
37.193.134.104
178.65.210.178
31.130.202.80
94.228.44.113
161.69.47.4
210.75.14.146

输出comm -13 <(sort old.txt) <(sort new.txt)

161.69.47.4
173.224.120.84
178.65.210.178
210.75.14.146
31.130.202.80
37.193.134.104
68.142.243.103
94.228.44.113
98.139.134.96
98.139.134.97
98.139.134.98
98.139.134.99

该标志-1抑制第一个文件中特有的行,该标志-3抑制两个文件中的行,并且该comm实用程序要求文件按排序顺序排列,即对它们都进行排序。

相关内容