how to rearrange the blocks of a text file columnwise

Viewed 65

Hii experts another problem i generally face in rearranging my text file.

my text file is arranged as written below.

>
1
2
3
>
2
3
4
>
1
4
5 

But i need to rearrange the above file by bringing the last block to the first column, before last block to the second column etc. as given below:can anybody suggest a better solution for same.Thanks in advance.

1 2 1
4 3 2
5 4 3
1 Answers
$ cat tst.awk
/^>/ {
    numRows = 0
    ++numCols
    next
}
{ vals[++numRows,numCols] = $1 }
END {
    for (rowNr=1; rowNr<=numRows; rowNr++) {
        for (colNr=numCols; colNr>0; colNr--) {
            printf "%s%s", vals[rowNr,colNr], (colNr>1 ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk file
1 2 1
4 3 2
5 4 3

EDIT: to create a shell script do do the above, store this in a file named foo:

#!/usr/bin/env bash

awk '
    /^>/ {
        numRows = 0
        ++numCols
        next
    }
    { vals[++numRows,numCols] = $1 }
    END {
        for (rowNr=1; rowNr<=numRows; rowNr++) {
            for (colNr=numCols; colNr>0; colNr--) {
                printf "%s%s", vals[rowNr,colNr], (colNr>1 ? OFS : ORS)
            }
        }
    }
' "${@:--}"

and then run it as foo file.

Related