Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Pivot text file with Perl

Posted on 2014-02-05
11
Medium Priority
?
351 Views
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.
0
Comment
Question by:dlnewman70
  • 6
  • 5
11 Comments
 
LVL 85

Expert Comment

by:ozo
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
0
 

Author Comment

by:dlnewman70
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”

error?
0
 

Author Comment

by:dlnewman70
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.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 85

Expert Comment

by:ozo
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
0
 

Accepted Solution

by:
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>;
chomp($line);
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>)
{
    chomp($line);
    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;
      }
}
close(INFILE);
close(OUTFILE);

exit(0)
0
 

Author Comment

by:dlnewman70
ID: 39836815
The above code that I wrote seemed to work better for our solution.
0
 
LVL 85

Expert Comment

by:ozo
ID: 39836836
What makes a solution 'better' for you?
0
 
LVL 85

Expert Comment

by:ozo
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
0
 

Author Comment

by:dlnewman70
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.
0
 
LVL 85

Expert Comment

by:ozo
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.
0
 

Author Closing Comment

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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

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…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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

916 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