Search code examples
linuxbashawktexttranspose

In bash how to move row field to column in a text file


I have a .txt file with this record:

field_1        value01a value01b value01c
field_2        value02
field_3        value03a value03b value03c

field_1        value11
field_2        value12a value12b 
field_3        value13

field_1        value21
field_2        value22
field_3        value23

...

field_1        valuen1
field_2        valuen2
field_3        valuen3

I would like to convert them like that:

field1                      field2            field3
value01a value01b value01c  valu02            value03a value03b value03c 
value11                     value12a value12b value13
value21                     value22           value23
...
valuen1                     valuen2           valuen3

I have tried something like:

awk '{for (i = 1; i <NR; i ++) FNR == i {print i, $ (i + 1)}}' filename

or like

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
    }
 }'

but i can't get it to work

I would like the values to be transposed and that each tuple of values associated with a specific field is aligned with the others

Any suggestions?

Thank you in advance


Solution

  • I have downloaded your bigger sample file. And here is what I have come up with:

    awk -v OFS='\t' -v RS= '
    ((n = split($0, a, / {2,}| *\n/)) % 2) == 0 {
       # print header
       if (NR==1)
          for (i=1; i<=n; i+=2)
             printf "%s", a[i] (i < n-1 ? OFS : ORS)
       # print all records
       for (i=2; i<=n; i+=2)
          printf "%s", a[i] (i < n ? OFS : ORS)
    }' reclamiTestFile.txt | column -t -s $'\t'
    

    Code Demo