LeetCode194 solution

How to transpose a file with bash

The original problem is https://leetcode.com/problems/transpose-file/.

This question is difficult for one who is not familiar with the bash tools, such as awk.

The first time I tried with a column-by-column handling with sed:

file='file.txt'
cols=`head -n 1 $file | wc -w`
for (( i=1; i <= $cols; i++))
    do cut -d ' ' -f $i $file | tr $'\n' $'\t' | sed -e "s/\t$/\n/g"
done

when I ran into the error Exceeds memory limits.

Finally I tried with awk, and solved the question.

The solution:

awk '
{ 
   for (i=1; i<=NF; i++)  {
       a[NR,i] = $i
   }
}
END {    
   for(j=1; j<=NF; j++) {
       str=a[1,j]
       for(i=2; i<=NR; i++){
           str=str" "a[i,j];
       }
       print str
   }
}' file.txt