2016-09-20 105 views
1

我想不出在bash shell中做到這一點的方法,並且準備在C中做到這一點。但也許你們有一個聰明的把戲......我有兩列X/Y位置和一列數據,我想只保留矩陣形式的數據。把數據以矩陣形式存入

例子:

0 0 A 
1 0 B 
2 0 C 
0 1 D 
1 1 E 
2 1 F 
0 2 G 
1 2 H 
2 2 I 
0 3 J 
1 3 K 
2 3 L 

應該變成:

A B C 
D E F 
G H I 
J K L 

(或其換位,我不在乎)。 我不知道這個操作的名稱,但基本上,當第二列更改值時,應該有一個新行。

+1

'TR -d '[0-9]'

+0

是的,我可以事先知道列的數量,以便工作。令人難以置信的簡單。謝謝。 – dargaud

回答

1

一個與cutpr

$ cut -d ' ' -f 3 test|pr -3 -a -t -s' ' 
A B C 
D E F 
G H I 
J K L 
  • cut' '分隔符僅打印第3列。
  • pr-3列,-a跨越而不是下降,-t抑制頁眉和頁腳,' '分離
0

這是一種方法用awk:

$ awk 'p==$2&&s{s=s OFS $3;next}s{print s}{s=$3;p=$2}END{print s}' file 
A B C 
D E F 
G H I 
J K L 
0

假設你的格式是「行列值」,並推廣你的 問題數據,其中的隨機流 位置不以特定的順序到達的行和列,您可以嘗試這個腳本

#!/bin/bash 

declare -A values # parameter "values" is an "A"rray 
rmax=0 cmax=0  # initial count of rows and columns 

# read from standard input 3 values per line 
while read r c v ; do 
    # store the value just readen 
    values[$c,$r]=$v 
    # possibly update the final number of rows and columns 
    [ $r -gt $rmax ] && rmax=$r 
    [ $c -gt $cmax ] && cmax=$c 
done 

# double do loop on rows and columns, swap cycles if you prefer the transpose 
for r in `seq 0 $rmax` ; do 
    for c in `seq 0 $cmax` ; do 
    # array parameters are undefined if not assigned, 
    # it is possible to assign a def value using the ":-" syntax 
    # in parameter substitution 
     printf "%5s" ${values[$c,$r]:-"----"} 
    done 
    printf "\n" 
done 

如果你不喜歡的破折號,只需要使用01用法

$ echo '0 2 e 
3 1 f 
1 0 g' | ./the_script 
---- ---- e 
    g ---- ---- 
---- ---- ---- 
---- f ---- 
$