How to Transpose a File in Bash (With Example)


Often you may want to use Bash to transpose the rows and columns of a particular file.

One of the easiest ways to do so is by using the following syntax with awk:

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

This particular example will transpose the rows and columns of the file named stats.txt.

To get this script to work with your own file, simply replace stats.txt with the name of your own file that you’d like to transpose.

The following example shows how to use this syntax in practice.

Example: How to Transpose a File in Bash

Suppose that we have a CSV file in our current directory named stats.txt that contains information about various basketball players.

We can use the cat command to view the contents of this file:

Suppose that we would like to transpose the rows and columns of this file.

We can use the following syntax to do so:

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

The following screenshot shows how to use this syntax in practice:

Bash transpose file

From the output we can see that we have successfully transposed the rows and columns of the file.

The teams are now shown as the column names and the various statistics (Points, Assists, Rebounds) for the players are now shown as the row names.

Feel free to replace stats.txt with the name of your own file that you would like to transpose.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Filter for Lines in File that Start with Specific String
Bash: How to Filter CSV File Based on Column Value
Bash: How to Extract Specific Columns from CSV File

Leave a Reply