2017-04-11 26 views
0

我想量化一個非常大的矩陣的變量。 例如,假設我有量化選定列中的變量

1 Blue 
2 Blue 
3 Blue 
4 Red 
5 Red 
6 Yellow 

而且我想獲得:

1-3 Blue 
4-5 Red 
6-6 Yellow 

這是可能用awk?

回答

1

在AWK:

$ awk ' 
{ 
    if(min[$2]=="" || $1<min[$2]) # compare for min 
     min[$2]=$1 
    if(max[$2]=="" || $1>max[$2]) # compare for max 
     max[$2]=$1 
} 
END { 
    for(i in min)     # output loop 
     print min[i] "-" max[i], i 
}' foo 

輸出:

4-5 Red 
1-3 Blue 
6-6 Yellow 

輸出順序是隨機的。將它管到sort訂購輸出。

2
$ awk '$2!=p{if (s) print s"-"e, p; s=$1} {e=$1; p=$2} END{print s"-"e, p}' file 
1-3 Blue 
4-5 Red 
6-6 Yellow 
2

其不需要排序或分組輸入

f() { sort -k2 -k1,1n$1 "$2"; }; paste <(f "" file) <(f "r" file) | 
awk '!a[$2]++{print $1"-"$3,$2}' 

1-3 Blue 
4-5 Red 
6-6 Yellow 
替代