Text-Processing

按列值轉置 cvs 文件

  • October 19, 2016

輸入:

X Y
1 11
1 12
2 21
2 22

期望的輸出:

11 12
21 22

我想通過第 1 列的值轉置 cvs 文件。在此範例中,對於 X = 1,將 (11, 12)^T 轉置為 (11, 12); 對於 X = 2,將 (21, 22)^T 轉置為 (21, 22)

perl

perl -lane '
   push @{$rows{$F[0]}}, $F[1] if $. > 1
 } END {
   $, = " ";
   print @{$rows{$_}} for (sort keys %rows);
' file

awk,假設輸入按第 1 列排序:

awk '
   NR == 1 {next}
   NR == 2 {key = $1} 
   $1 != key {print ""; key = $1} 
   {printf "%s ", $2} 
   END {print ""}
' file

引用自:https://unix.stackexchange.com/questions/317507