2014-09-05 53 views
1

我有一個長長的清單100K在一定範圍內的IP地址+,從這個腳本的例子是:刪除在文本文件中的非重複的行

67.0.105.76 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.123.150 0 
67.0.105.76 0 
67.0.123.150 0 
67.0.163.127 0 
67.0.123.150 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.163.127 0 
67.0.105.76 0 
67.0.105.76 0 
67.0.105.76 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.232.158 0 
67.0.105.76 0 
67.0.143.13 0 

從這個名單,我想刪除任何IP的是沒有列出多次,所以說我想從上面的列表中刪除所有ips未列出5次或更多次。然後,它將輸出:

67.0.105.76 0 
67.0.123.150 0 
67.0.163.127 0 
67.0.232.158 0 

我試圖實現在Linux中使用這個SED/uniq的,但無法找到一個方法來做到這一點,將Python腳本或如需要此或爲有一種可能的方式使用sed/uniq?

使用sort -u 100kfile,它能夠刪除所有重複項,但它仍然保留單個IP。

回答

4

使用sortuniqawk

[email protected]: ~ sort data.txt | uniq -c | awk '{if ($1 > 4) print $2,$3}' 
67.0.105.76 0 
67.0.123.150 0 
67.0.163.127 0 
67.0.232.158 0 
+0

似乎錯過了一些,如果他們分散出來,我試了它在我的大名單,它似乎是複製一些仍然http://puu.sh/bn8Kl/bc8b1d6bf7.txt – user1372896 2014-09-05 22:54:10

+0

@ user1372896請參閱我的更新。 – uselpa 2014-09-05 22:56:10

+1

+1:你可以完全用'awk'來完成。 'awk'{ips [$ 0] ++} END {for(ip in ips)if(ips [ip]> = 5)print ip}'data.txt' – 2014-09-05 23:16:54

0

純Python的解決方案,使用從collections moduleCounter工具。

我不知道這將如何與100k地址,但你可以放棄它。

from collections import Counter 

with open('ip_file.txt', 'r') as f: 
    ip_list  = map(lambda x: x.strip(), f.readlines()) 
    ip_by_count = Counter(ip_list) 

    for ip in ip_by_count: 
     if ip_by_count[ip] > 1: 
      print ip 

或者一種替代方法:維護兩套,其中一套IP看上去只有一次,另一套用於IP至少兩次。打印的IP,當我們看到它的第二個時間,跳過所有隨後出現:

known_dupes = set() 
single_ips = set() 

with open('ip_file.txt', 'r') as f: 
    ip_list = map(lambda x: x.strip(), f.readlines()) 

    for ip in ip_list: 
     if ip in known_dupes: 
      continue 
     elif ip in single_ips: 
      print ip 
      known_dupes.add(ip) 
      single_ips.remove(ip) 
     else: 
      single_ips.add(ip) 

我懷疑第一可能是快,但我還沒有嘗試過在一個大的文件進行檢查。

0

這裏有一個簡單的方法來做到這一點在awk

awk '{a[$0]++} END {for (i in a) if (a[i]>4) print i}' file 
67.0.232.158 0 
67.0.105.76 0 
67.0.163.127 0 
67.0.123.150 0 

計數每一個唯一的IP和存儲的號碼在一個數組a
如果有更多的則4命中,打印。
它應該會更快然後sortuniqawk

PS我沒有看到我張貼了這個之後,其同jaypal張貼評論。