Transposing columns and rows in Unix/Linux

There is no direct command to transpose columns/rows but you can easily do it using command tr. This is often necessary when you want to find out total number of columns or ordinal number of some specific column

For example you want to number columns in a file

[sergeyma@dev1456 ~/scripts] cat f1
column1 column2 column3
23 12 12
3 23 32

Command below outputs first line of file using head and then transposes this line by replacing tab with end of line.

[sergeyma@dev1456 ~/scripts] head -n 1 | tr "\t" "\n"

In this code, head outputs first line of file, tr replaces tab with end of line and then add line numbers in output using nl.

[sergeyma@ ~/scripts] head -n 1 f1 | tr "\t" "\n" | nl
1 column1
2 column2
3 column3
This entry was posted in productivity. Bookmark the permalink.