-3

Script tried:

perl -nle '
if($. == 1)
{ (@a)=/([\w - .]+)(?=,|\s*$)/g }
else
{
    (@b)=/([\w - .]+)(?=,|\s*$)/g;
    print "$a[0]|$b[0]|$b[1]|$b[2}|$a[$_]|$b[$_+3]" foreach (0..$#a)
}
' ip.txt >op.txt

input data :

src,FI,QMA,PCG,PCC,PREI,G T
PIM2016.csv,MMR.S T - RED,334,114,120,34,123,725

output with latest script:

SRC|PIM2016.csv|MMRPPS|RED|SRC|334
SRC|PIM2016.csv|MMRPPS|RED|FI|114
SRC|PIM2016.csv|MMRPPS|RED|QMA|120
SRC|PIM2016.csv|MMRPPS|RED|PCG|34
SRC|PIM2016.csv|MMRPPS|RED|PCC|123
SRC|PIM2016.csv|MMRPPS|RED|PREI|725
SRC|PIM2016.csv|MMRPPS|RED|G T|

Required output:

SRC|PIM2016.csv|MMRPPS|S T - RED|FI|334
SRC|PIM2016.csv|MMRPPS|S T - RED|QMA|114
SRC|PIM2016.csv|MMRPPS|S T - RED|PCG|120
SRC|PIM2016.csv|MMRPPS|S T - RED|PCC|34
SRC|PIM2016.csv|MMRPPS|S T - RED|PREI|123
SRC|PIM2016.csv|MMRPPS|S T - RED|G T|725
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
udayadevan
  • 23
  • 5
  • 2
    Why have you tagged with [tag:awk] if your current attempt is in [tag:perl]? – Tom Fenech Sep 23 '16 at 09:29
  • 3
    @TomFenech : apparently the spec has changed :-) http://stackoverflow.com/questions/39612637/unix-awk-scripting-to-convert-columns-to-rows . Good luck to all. – shellter Sep 23 '16 at 10:01

1 Answers1

1

I think your life gets a lot easier if you know about split()

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my (@head);
while (<>) {
  chomp;
  if ($. == 1) {
    @head = split /,/;
    next;
  }

  my @data = split /,/;

  say "$head[0]|$data[0]|$data[1]|$data[2]|$head[$_]|$data[$_+2]" for (1 .. $#head);
}

I've written it as a program rather than as a command line as I think it's too long to be run on the command line.

Also, I hope that the dot after "MMR" in your sample input is a typo for a comma. If that's not the case it gets a little more complex - but not very much.

Oh, and there's no "PPS" in your sample input, so I've no idea where that comes from in your sample output.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97