Convert columns to rows in perl script

Hi All

I want to have a Perl script which convert columns to rows.
The Perl should should read the data from input file.
Suppose the input file is

7215484
date to date
173.3
A
1.50
2.23
8.45
10.14
2.00
4.50
2.50
31.32
7216154
month to month
182.7
A
1.50
2.36
8.91
10.69
2.00
4.50
4.16
34.11
7216184
case to case
179.6
A
1.50
2.32
8.76
10.51
2.00
4.50
4.16
33.75
7216254
done with no error
193.0
A
1.50
2.49
9.41
11.29
2.00
4.50
4.16
35.35

and the output file wanted is

7215484	"date to date"	173.3	A	1.50	2.23	8.45	10.14	2.00	4.50	2.50	31.32
7216154	"month to month"	182.7	A	1.50	2.36	8.91	10.69	2.00	4.50	4.16	34.11
7216184	"case to case"	179.6	A	1.50	2.32	8.76	10.51	2.00	4.50	4.16	33.75
7216254	"done with no error"	193.0	A	1.50	2.49	9.41	11.29	2.00	4.50	4.16	35.35

With awk, you can use:

awk '{if(a!=""){a=a "\t" $0}else{a=$0}} NR%12 == 0{print a; a=""}' infile

With perl, the code is a little bit more verbose.

perl -le 'while(<>){chomp; if($a!=""){$a="$a\t$_"}else{$a=$_} if($.%12==0){print $a; $a=""}}' infile

Note: the second column is not quoted, I don't think it needs to be, because I use the \t character as field separator.

Alternatively:

awk 'ORS=!(NR%12)?RS:"\t"' infile
paste - - - - - - - - - - - - < infile
perl -lpe '$\=!($.%12)?"\n":"\t"' infile

Cool, you just changed the output record separator accordingly.
I am just using the tools, while you are playing with the tools.
That was amazing!

1 Like