nr0mx has asked for the wisdom of the Perl Monks concerning the following question:

I have the below script that splits a line on a comma, and adds two new columns in the line by copying column 3 & 4. I need to turn this into a in-place edit one-liner. A regexp seems to be the way to go, but I can't see the solution. Any help appreciated.
while(<DATA>) { my @array = split(/,/); print join(',',@array[0..3]),",$array[3],$array[4],",join(',',@arr +ay[4..$#array]); } __DATA__ 20110_1,1155,30,20110_1_3,0,0,65,0,0,99,20,20,14,0,23,2001-08-01 00:00 +,2001-09-18 00:00,0,,0, 20110_2,1155,30,20110_2_3,0,0,65,0,0,99,20,20,14,0,23,2001-08-01 00:00 +,2001-09-18 00:00,0,,0, 20110_3,1155,30,20110_3_3,0,0,65,0,0,99,20,20,14,0,23,2001-08-01 00:00 +,2001-09-18 00:00,0,,0,

Replies are listed 'Best First'.
Re: Need help constructing a one-liner
by jeffa (Bishop) on Dec 02, 2003 at 13:29 UTC
    How about using autosplit mode?
    perl -F, -lape'join(",",@F[0..3],$F[3],$F[4],@F[4..$#F])' data.txt
    I like to start out with something like:
    perl -F, -MData::Dumper -lape'Dumper \@F' data.txt
    To make sure that i am populating @F correctly first, then move on. Once you feel comfortable, you can add inplace editting:
    perl -F, -lapi.bak -e'$_=join(",",@F[0..3],$F[3],$F[4],@F[4..$#F])' da +ta.txt

    UPDATE:
    replaced -lane with -lape and dropped print ... silly /me ;)

    UPDATE2:
    fixed error pointed out by nr0mx and duff ... thanks guys :)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      You know, you can do this too:

      perl -F, -lapi.bak -e'$_=join(",",@F[0..3,3,4,4..$#F])' data.txt

      Not that we're golfing or anything :-)

      Oh, and you forgot your assignment to $_. Otherwise it won't print what you want

      Thanks, that worked splendidly!
      I had to reassign the join back to $_, but ths is exactly what I had been looking for.
Re: Need help constructing a one-liner
by exussum0 (Vicar) on Dec 02, 2003 at 12:59 UTC
    What you have now would work as a one liner, assuming you are going for perl -e. If you are playing golf, I'd suspect trying somethign like..

    $_=~s/^(([^,]+,){4})([^,]+,[^,]+)/$1"$3"/;

    would work too. Nothing is wrong with what you have though. I think it's much clearer.


    Play that funky music white boy..