famedoro
famedoro

Reputation: 1241

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

Upvotes: 1

Views: 213

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following, written and tested with shown samples in GNU awk.

awk '
{
  first=$1
  $1=""
  sub(/^ +/,"")
  if(!arr[first]++){
    ++indArr
    counter[indArr]=first
  }
  ++count[first]
  arr[first OFS count[first]]=$0
}
END{
  for(j=1;j<=indArr;j++){
    printf("%s\t%s",counter[j],j==indArr?ORS:"\t")
  }
  for(i=1;i<=FNR;i++){
     for(j=1;j<=indArr;j++){
       if(arr[counter[j] OFS i]){
          printf("%s\t%s",arr[counter[j] OFS i],j==indArr?ORS:"\t")
       }
     }
  }
}' Input_file | column -t -s $'\t'

column command is taken from @anubhava sir's answer here.

Upvotes: 2

anubhava
anubhava

Reputation: 785186

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

Upvotes: 3

Related Questions