Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Pivot text file with Perl

Posted on 2014-02-05
Medium Priority
Last Modified: 2014-04-30
I have a tab delimited file that has three rows of data. There are multiple columns with data. It looks like this:

Month    Year    PartnerName   Air    Hotel
12           2013  Partner A          10    20
12           2013  Partner B           5      3

I need to somehow transpose the file so it ends up like this:

12        2013      Partner A       Air      10
12        2013      Partner A       Hotel    20
12        2013      Partner B       Air         5
12        2013      Partner B       Hotel    3

So it is taking the "data" columns and pivoting those to rows.
Question by:dlnewman70
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
LVL 84

Expert Comment

ID: 39836112
perl -ane '@h?((@h[0,1]=splice@F,-2),print "@F @h[-2,0]\n@F @h[-1,1]\n"):(@h=@F)' file

Author Comment

ID: 39836332
I am trying to run this on Windows. Would there be any reason that this would cause a

“Can't find string terminator ”'“ anywhere before EOF at -e line 1”


Author Comment

ID: 39836345
I have swapped the single quote with double quotes and the double quotes with single quotes and it appears to run, but I don't see the changes on the file.
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 84

Expert Comment

ID: 39836543
perl -ane "@h?((@h[0,1]=splice@F,-2),print qq'@F @h[-2,0]\n@F @h[-1,1]\n'):(@h=@F)" file

If you want to change file:
perl -i.bak -ane "@h?((@h[0,1]=splice@F,-2),print qq'@F @h[-2,0]\n@F @h[-1,1]\n'):(@h=@F)" file

Accepted Solution

dlnewman70 earned 0 total points
ID: 39836803
# use strict;
use warnings;

use Fcntl ':flock'; # contains LOCK_EX (2) and LOCK_UN (8) constants
$beforefile = $ARGV[0];
$afterfile = $ARGV[1];

open (INFILE, $beforefile);
open (OUTFILE,">", $afterfile);

my $line = <INFILE>;
my @header_item = split(/\t/, $line);
my $size = $#header_item + 1;
die("Invalid header line.\n") if (@header_item < 2);

my %new_header_item = ();
my %data = ();

while ($line = <INFILE>)
    my @item = split(/\t/, $line);

      my @h = sort keys(%new_header_item);
      my $counter = 4;

      while ($counter < $size)
      print OUTFILE $item[0]."\t".$item[1]."\t".$item[2]."\t".$item[3]."\t".$header_item[$counter].' '.join(' ', @h).$item[$counter]."\n";
      $counter = $counter + 1;


Author Comment

ID: 39836815
The above code that I wrote seemed to work better for our solution.
LVL 84

Expert Comment

ID: 39836836
What makes a solution 'better' for you?
LVL 84

Expert Comment

ID: 39836998
On the example in the original question, the code in http:#a39836803 fails with Invalid header line.
and if the spaces in the example are changed to tabs, it still does not produce the result you said you wanted it to ends up like.
It also has several expressions that produce no useful effect.

Do you want three 'fixed' tab delimited columns and an unlimited number of 'transposed' columns?
perl -F"\t" -lane '$"="\t";if(@h){@h{@h}=splice@F,3;print "@F\t$_\t$h{$_}" for @h}else{@h=@F[3..$#F]}'  beforefile > afterfile

Author Comment

ID: 39837072
Savant, "better" for us is basically giving me the desired result. I am not fully versed either on the single line solution. Still learning...

On the solution ozo provided it wasn't giving me the exact results I was expecting.

I appreciate you all jumping in for support and for ideas.
LVL 84

Expert Comment

ID: 39837680
On the example in the original question, the code in http:#a39837072 gave me the desired result that was specified, and the code in http:#a39836803 did not.
If you wish to clarify either the initial conditions or the desired result, we can adjust our suggestions accordingly.

Author Closing Comment

ID: 40031519
This code did what I needed it to do.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans

664 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question