title: An efficient way to transpose a file in Bash
body: <p>I have a huge tab-separated file formatted like this</p>
  
  <pre><code>X column1 column2 column3
  row1 0 1 2
  row2 3 4 5
  row3 6 7 8
  row4 9 10 11
  </code></pre>
  
  <p>I would like to <em>transpose</em> it in an efficient way using only bash commands (I could write a ten or so lines Perl script to do that, but it should be slower to execute than the native bash functions). So the output should look like</p>
  
  <pre><code>X row1 row2 row3 row4
  column1 0 3 6 9
  column2 1 4 7 10
  column3 2 5 8 11
  </code></pre>
  
  <p>I thought of a solution like this</p>
  
  <pre><code>cols=`head -n 1 input | wc -w`
  for (( i=1; i &lt;= $cols; i++))
  do cut -f $i input | tr $'\n' $'\t' | sed -e "s/\t$/\n/g" &gt;&gt; output
  done
  </code></pre>
  
  <p>But it's slow and doesn't seem the most efficient solution. I've seen a solution for vi in <a href="https://stackoverflow.com/questions/704130/can-i-transpose-a-file-in-vim">this post</a>, but it's still over-slow. Any thoughts/suggestions/brilliant ideas? :-)</p>