主角
>> Scribe设置
Cron重复执行相同的任务,强制一个无辜的netstat显示网络状态(netstat -n)。管道随后必须获取信息并将其传递给身份文本处理实用程序(| grep tcp | awk '{ print $5 }' | cut -d "." -f-4)。>>必须将重要的结果抄写到文件中。由于殿下,管理,是一个懒惰和容易恼怒的统治者,>>只想抄写新的信息到文件。
*/1 * * * * netstat -n | grep tcp | awk '{ print $5 }' | cut -d "." -f-4 >> /tmp/file>>自言自语
To append, or not append, that is the question:
Whether 'tis new information to bother The Admin with
and earn an outrageous Fortune,
Or to take Arms against `netstat` and the others,
And by opposing, ignore them? To die: to sleep;注意:对于所有像我一样理解哈姆雷特有问题的人,问题是,如何检查字符串是否已经包含在文件中,如果没有,如何将其附加到文件中?
发布于 2013-09-21 10:55:14
除非您正在处理一个非常大的文件,否则可以使用uniq命令从文件中删除重复行。这意味着您也将对文件进行排序,我不知道这对您是有利的还是不利的:
netstat -n | grep tcp | awk '{ print $5 }' | cut -d "." -f-4 >> /tmp/file && sort /tmp/file | uniq > /tmp/file.uniq这将给出在/tmp/file.uniq中没有重复的排序结果。
发布于 2013-09-21 19:49:27
What a piece of work is piping, how easy to reason about,
how infinite in use cases, in bash and script,
how elegant and admirable in action,
how like a vim in flexibility,
how like a gnu!以下是一个略有不同的观点:
netstat -n | awk -F"[\t .]+" '/tcp/ {print $9"."$10"."$11"."$12}' | sort -nu | while read ip; do if ! grep -q $ip /tmp/file; then echo $ip >> /tmp/file; fi; done;解释:
awk -F"[\t .]+" '/tcp/ {print $9"."$10"."$11"."$12}'Awk将输入字符串拆分为制表符和".“。输入字符串由包含"tcp“的行过滤(而不是使用单独的grep调用)。最后,生成的输出字段与点连接并打印出来。
sort -nu对IP进行数字排序,并创建一组唯一的条目。这样就不需要单独的uniq命令了。
if ! grep -q $ip /tmp/file; then echo $ip >> /tmp/file; fi;文件中的ip的Greps,如果它找不到它,则会追加ip。
注意:这个解决方案不会在每次运行后删除旧条目并清理文件--它只是附加--正如您的问题所暗示的那样。
https://stackoverflow.com/questions/18931423
复制相似问题