1

I have a file like this:

column1   column2   column3  column4   column5
 5e-05   1e-05 0.00083   4e-05 0.00021
 6e-05   3e-05 1.00083   2e-05 1.00021

And I need to re-format it to print and output like this.

column1   5e-05      6e-05
column2   1e-05      3e-05
column3   0.00083    1.00083
column4   4e-05      2e-05
column5   0.00021    1.00021

I was trying using

 tr ' ' '\n' | 
 pr -3t

but with no success until now.

I find a solution :

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

      }
 }' file

but the output looks like this:

column1 5e-05 5e-05
column2 1e-05 1e-05
column3 0.00083 0.00083
column4 4e-05 4e-05
column5 0.00021 0.00021

And I want that the numbers of the output are formatted

  • 2
    If you search transpose you will see this has been pretty well covered here before – steeldriver Jun 2 '16 at 23:30
  • 1
    There are several answers with scripts, but i cannot not mention how great GNU datamash is for this purpose. datamash is around for not very long, and several answers do not mention it. – grochmal Jun 2 '16 at 23:39
  • 1
    Tuck on egrep -v '^$' | to the first line, to exclude the blank lines made by tr. – Ralph Rönnquist Jun 3 '16 at 0:25
  • 1
    ... or if your version of tr supports the -s (squeeze) flag, tr -s ' ' '\n' < yourfile | pr -3t – steeldriver Jun 3 '16 at 2:50
  • Sorry I don't understand what you mean by "one row up the column" - I appear to get exactly the desired output from your posted input. Does your input have a mix of spaces and tabs? if so, you may need to replace tr -s ' ' '\n' with tr -s '[:space:]' '\n' – steeldriver Jun 3 '16 at 3:04
2

I found two answers to the problem proposed:

The first one propose by @steeldriver:

    tr -s ' ' '\n' < file | pr -3t

And the second one, I found in another discussionabout transpose matrix elements:

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

  }
 }' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.