I want to transpose the rows of a file to the columns (every characters include spaces), i.e.:
input:
abcdefg
123 456
output:
a1
b2
c3
d
e4
f5
g6
I wrote a script:
#!/bin/csh -f
set num=`cat $1 |wc -l`
echo "$num rows of $1 transposing to columns..."
if ( -f temp1 ) then
rm temp1
touch temp1
else
touch temp1
endif
set i=1
set j=2
while ($i <= $num)
# read a row, transpose to a column
sed -n "$i p" $1 | sed 's/\n*/\n/g' > temp
# merge columns in files
paste temp$i temp > temp$j
rm temp$i
@ i++
@ j++
end
mv temp$i $1.transposed
rm temp
echo "Done!"
It works, but the paste command has several problems:
It inserts an empty column when appends a new column;
The columns length need be the same;
And the biggest problem is since the script keeps read and write temp files, it is very slow, the files I want to transpose have tens of thousands of rows, so it takes nearly an hour to proceed large files.
Dear guys;
This solution provided by danmero is not working on solaries were my system can't take FS="" as null value??? any exeplination please!!!
I am working on the below station type:-
SunOS server2 5.10 Generic_118833-36 sun4u sparc SUNW,Netra-210
BR
this code is not working for me but radoulov code is working find because he is using the substr command ....
but my question is how I can set the FS variable to null FS="" using solaries 10??
#!/usr/bin/perl -w
# arrayref for columns
my $cols = [];
# counter for characters
my $counter = 0;
# get file handle
open FILE, "<in.txt";
# iterate over lines in file
foreach my $line (<FILE>)
{
# remove line feed
chomp($line);
# create array containing each char on line
my @chars = split(//,$line);
# create arrayref for characters
$cols->[$counter]=[];
# iterate over characters, pushing each into an
# index of the arrayref just created
for my $char (@chars)
{
push(@{$cols->[$counter]},$char);
}
# iterate the counter for the next line
$counter++;
}
# close the file handle
close FILE;
# open a new file handle for output
open OUT, ">output.txt";
# iterate over the columns (0 thru max index of array storing characters at index 0)
for my $i ( 0 .. @{$cols->[0]} -1)
{
# iterate over the lines (0 thru max index of array storing lines)
for my $j ( 0 .. @$cols -1 )
{
# print character at line $j, column $i
print OUT $cols->[$j]->[$i];
}
# print linefeed
print OUT "\n";
}
# close the filehandle
close OUT;
#!/usr/bin/perl -w
my $cols = [];
my $counter = 0;
open FILE, "<in.txt";
foreach my $line (<FILE>)
{
chomp($line);
my @chars = split(//,$line);
$cols->[$counter]=[];
for my $char (@chars)
{
push(@{$cols->[$counter]},$char);
}
$counter++;
}
close FILE;
open OUT, ">output.txt";
for my $i ( 0 .. @{$cols->[0]} -1)
{
for my $j ( 0 .. @$cols -1 )
{
print OUT $cols->[$j]->[$i];
}
print OUT "\n";
}
close OUT;