Can we transpose rows to columns? Fields within row are separated by a comma.
yes, we can!
but how?
This has been discussed very recently, and an Awk solution was presented. Here's a Ruby one:
ruby -F, -lane '
BEGIN{$a=[]};$a.concat([$F]);END{$a.transpose.each{|x|puts x.join(",")}}
' infile
1,2,3,4
5,6,7,8
becomes
1,5
2,6
3,7
4,8
Following Shell script works...
There should be a file namely "data" with following content
1,2,3
4,5,6
7,8,9
then after running the script the content of file will be
1,4,7
2,5,8
3,6,9
num=$(awk -F"," 'NR==1 { print NF }' data)
print $num
i=1
while (( $i <= $num ))
do
newline=''
for val in $(cut -d"," -f$i data)
do
newline=$newline$val","
done
nline=`print ${newline%?}`
print $nline >> tmpdata
(( i = i + 1 ))
done
mv tmpdata data
I have one more thing to ask on same script...
what if the rows and coulmns are not equal , then the script fails...
like input file
abc,abc1,abcd3
pqrs,pqr
1,2,3,4,5,6,7,8,9,10,11
Pls suggest ....
Regards,
Aparna
Put this is a file - testawk.awk
BEGIN {FS=","}
{
for (i=1;i<=NF;i++)
{
arr[NR,i]=$i;
if(big <= NF)
big=NF;
}
}
END {
for(i=1;i<=big;i++)
{
for(j=1;j<=NR;j++)
{
printf("%s\t",arr[j,i]);
}
printf("\n");
}
}
awk -f testawk.awk testfile
Another way I found -
echo 1,2,3 | awk -F"," '{gsub(/,/,"\n",$0);print $0}'
... and if you have multiple rows?
Yes, not possible.
If you want to keep the format of the input file (fields separated by a comma) for the output file, the solution from ranj@chn can be modified a little bit :
BEGIN {FS=OFS=","}
{
for (i=1;i<=NF;i++)
{
arr[NR,i]=$i;
if(big <= NF)
big=NF;
}
}
END {
for(i=1;i<=big;i++)
{
for(j=1;j<=NR;j++)
{
printf("%s%s",arr[j,i], (j==NR ? "" : OFS));
}
print "";
}
}
Input:
abc,abc1,abcd3
pqrs,pqr
1,2,3,4,5,6,7,8,9,10,11
Output:
abc,pqrs,1
abc1,pqr,2
abcd3,,3
,,4
,,5
,,6
,,7
,,8
,,9
,,10
,,11