LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   transform rows into columns in bash (https://www.linuxquestions.org/questions/linux-newbie-8/transform-rows-into-columns-in-bash-894561/)

xeon123 07-29-2011 07:47 PM

transform rows into columns in bash
 
Hi,

I would like to transform rows into columns from a file in bash.

This is the file
Code:

param1        value1
param2        value2
param3        value3

And I like to become like this:

Code:

param1  param2    param3
value1  value2    value3

How can i do this?

Tinkster 07-29-2011 09:23 PM

Quote:

Originally Posted by xeon123 (Post 4428931)
Hi,

I would like to transform rows into columns from a file in bash.

This is the file
Code:

param1        value1
param2        value2
param3        value3

And I like to become like this:

Code:

param1  param2    param3
value1  value2    value3

How can i do this?


Something like this?
Code:

{
  for (i=1;i<=NF;i++)
  {
    arr[NR,i]=$i;
    if(nf<= NF)
      nf=NF;
  }
  nr=NR
}

END {
  for(i=1;i<=nf;i++)
  {
    for(j=1;j<=nr;j++)
    {
      printf("%s\t",arr[j,i]);
    }
    printf("\n");
  }
}



Cheers,
Tink

fpmurphy 07-30-2011 12:14 AM

The problem with bash is that it does not support multi-dimensional arrays - so you have to use awk, perl, pthyon, ruby or suchlike to transpose the contents of your file.

Here is one way of doing what you want to do using Python and zip*
Code:

!/usr/bin/python

inputList = []

infile = open('infile')
for lines in infile:
    fields = lines.split(None, 1)
    fieldsTuple = (fields[0], fields[1].rstrip())
    inputList.append(fieldsTuple)

infile.close()

inputList = zip(*inputList)

outfile = open("outfile", "w")
for items in inputList:
    for item in items:
        outfile.write(str(item) + ' ')
    outfile.write('\n')

outfile.close()

Infile:
Code:

"param1"  "value1"
"param2"  "value2"
"param3"  "value3"

Outfile:
Code:

"param1" "param2" "param3"
"value1" "value2" "value3"


igadoter 07-30-2011 02:12 AM

Code:

for i in 1 2 ; do cat input | cut -d' ' -f$i | paste -s >> output ; done
it works for me but it is ugly solution.

grail 07-30-2011 08:19 AM

Well as with the others my solution only works for the 2 column scenario as well:
Code:

awk '{print $1;s[NR]=$2}END{printf "\n";for(i in s)print s[i]}' ORS=" " file


All times are GMT -5. The time now is 10:28 PM.