2015-02-12 105 views
1

我在下面的表格數據:排序使用Linux命令

Sub: Size:14Val: 4644613 Some long string here 
Sub: Size:2Val: 19888493 Some other long string here 
Sub: Size:1Val: 6490281 Some other long string here1 
Sub: Size:1Val: 320829337 Some other long string here2 
Sub: Size:1Val: 50281086 Some other long string here3 
Sub: Size:1Val: 209077847 Some other long string here4 
Sub: Size:3Val: 320829337 Some other long string here2 
Sub: Size:3Val: 50281086 Some other long string here3 
Sub: Size:3Val: 209077847 Some other long string here4 

現在我想提取所有尺寸: - 從該文件中的信息。這是我想提取以下內容:

Size:14 
Size:2 
Size:1 
Size:1 
Size:1 
Size:1 
Size:3 
Size:3 
Size:3 

而我想找出所有與大小相關的值的出現次數。例如。 (i)按發生次數分類,(ii)按照與大小相關的值分類),一次發生一次,2次發生一次,1次發生四次等等))。這就是想要以排序的方式得到如下結果:

(i). sorted by number of occurences 
1->4 
3->3 
2->1 
14->1 

(ii). sorted by the value associated with Size: 
1->4 
2->1 
3->3 
14->1 

我寫了一個python程序,並能夠對它們進行排序。但我在想有沒有辦法使用像grep等linux命令來做同樣的事情?我使用的是Ubuntu 12.04。

回答

1

要提取大小字段,

grep -o 'Size:[0-9]*' data 

通過獨特的事件排序可以sort | uniq -c | sort -rn做,你可以做一些小的修改,以第一sort(即添加-t : -k2rn),並在年底離開關sort -rn按價值排序。使用簡單的sed腳本可以輕鬆地將最終輸出按要求的格式進行處理。

grep -o 'Size:[0-9]*' data | 
sort -t : -k2rn | uniq -c | 
sed 's/^ *//;s/\([1-9][0-9]*\) Size:\([0-9]*\)/\2->\1/'