2012-08-29 40 views
2

我需要幫助來解析像這樣的輸入。如何根據bash中的列變量解析輸入

192.168.0.168: 1 
192.168.0.158: 0 
192.168.0.198: 0 
192.168.0.148: 0 
192.168.0.158: 1 
192.168.0.168: 0 

如果任何ip的第二列中有1,我想刪除第二列有0,第一列有相同ip的那一行。所以我的輸出應該是這樣的。

192.168.0.168: 1 
192.168.0.198: 0 
192.168.0.148: 0 
192.168.0.158: 1 

我想這可以通過使用awk,sed等來完成,但我不知道該怎麼做。我希望我能正確解釋我的問題。謝謝...

回答

2

方式一:

awk ' 
    { 
     ips[ $1 ] = (ips[ $1 ] == 1) ? 1 : $2 
    } 
    END { 
     for (ip in ips) { 
      print ip, ips[ ip ] 
     } 
    } 
' infile 

國債收益率(輸出可能是無序的):

192.168.0.168: 1 
192.168.0.198: 0 
192.168.0.148: 0 
192.168.0.158: 1 
2

這可能會爲你工作(GNU SED):

cat -n file | 
sort -k2,2 -k3,3nr | 
sed ':a;$!N;/^\s*\S*\s*\(\S*\)\s*1\s*\n.*\1/s/\n.*0\s*//;ta;P;D' | 
sort -n | 
sed 's/^\s*\S*\s*//' 
1

Perl解決方案:

perl -nae '$h{ $F[0] } += $F[1] 
      }{ 
      print "$k ", $v ? 1 : 0, "\n" while ($k, $v) = each %h' 
1

一對夫婦的sort S的關係做:

sort file -r | sort -u -k1,1 

前者排序可以確保線路被排序使得第二列1行會先爲每個IP。

後一種排序將僅保留每個IP的第一個條目:-u - >唯一,-k1,1 - >僅限第一列。

+0

爲了保持在線訂購您可以使用_potong's_回答使用同樣的伎倆。首先對行進行編號並使用'cat -n',然後在第一列進行排序:'cat -n infile | sort -k2 -r | sort -u -k2,2 | sort -n |切-f2-'。 – Thor

1
awk '{a[$1]+=$2}END{for(i in a)print i,a[i]}' your_file 
1

功能的方法(Haskell的編程語言):

-- function that having the two sublists with '0' and '1' ips, 
-- filters and puts into the '1' 
-- sublist all the '0' ips that are not included in '1' 

fil [] result = result 
fil (x: xs) result | (init x `elem` (map init result)) == False = fil xs (x:result) 
      | otherwise = fil xs result 


-- function that filters '0' and '1' sublists 
getsublist alist character = filter (\x-> (last x) == character) alist 



> let a = ["192.168.0.168: 1", "192.168.0.158: 0", "192.168.0.198: 0", "192.168.0.148: 0", "192.168.0.158: 1", "192.168.0.168: 0"] 

> let b = getsublist a '0' 

> let c = getsublist a '1' 

> fil b c 

輸出:

["192.168.0.148: 0","192.168.0.198: 0","192.168.0.168: 1","192.168.0.158: 1"]