Solved

Pivot text file with Perl

Posted on 2014-02-05
11
331 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 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
# 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:dlnewman70
Comment Utility
The above code that I wrote seemed to work better for our solution.
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
What makes a solution 'better' for you?
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
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 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
This code did what I needed it to do.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

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…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
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…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

763 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now