O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transposing a matrix

Transposing a matrix is basically interchanging its rows with columns. In this example, we build a string using a  separator. Here, we use the fact that AWK variables are dynamic. We use a variable sep, which is empty initially on first execution, and then it is set to a semicolon. It will have that value from the second time the code executes onwards. The result is that at the end of the string, we will have a clean list of values with a semicolon at the desired place:

$ vi matrix.txta1;a2;a3;a4b1;b2;b3;b4c1;c2;c3;c4d1;d2;d3;d4$ vi transpose_matrix.awkBEGIN    {    FS = ";"    }{    for( i=1; i<=NF; i++ )    r[i]=r[i] sep $i    sep=FS}END    {    for( i=1; i<=NF; i++ )    {        print r[i]    }}$ awk -f transpose_matrix.awk matrix.txt

The output on execution ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required