问题描述:

Hey people of stackoverflow.

I've got a var i've got to place in every row when printing it into my CSV file and i've got no clue how to do this.

Example of CSV after transform

Name; Job; FunctionNumber; **Group**; Afdeling

ASD; ASD; 1; 12; Bewaking;

Group has to be repeaten with every row enter when printing into my CSV file.

EDIT: CSV Before transform

Name; Job; FunctionNumber; Afdeling

ASD; ASD; 1; Bewaking;

It's also probbaly for the best to show the code i use to retrieve the group number from the title of the source csv file.

 my $filespec = $TMP_Path;

my $dirname = dirname $TMP_Path;

my $filename = basename $TMP_Path;

my $groep = substr($filename,5,index($filename,'.')-5);

print $groep."\n";

网友答案:
#!/usr/bin/perl

use strict;
use warnings;

my $group="something";

while (<>) {
    # Trim end of line character
    chomp;

    # Define variables to hold each CSV field
    my ($f1,$f2,$f3,$f4);

    # Break line up on semicolons
    ($f1,$f2,$f3,$f4) = split(';');

    # Output with group in fourth field
    printf("$f1;$f2;$f3;$group;$f4\n");
}

Save as "go", then type:

chmod +x go
./go < yourfile
网友答案:

You want to insert both a new column heading and a repeating value under that column. Here's one option:

use strict;
use warnings;

my ( $header, $value ) = ( '**Group**', 12 );

while (<>) {
    my $insert = $. == 1 ? $header : $value;
    my @fields = split /;/;
    splice @fields, 3, 0, $insert;
    print join ';', @fields;
}

Usage: perl script.pl inFile [>outFile]

The last, optional parameter directs output to a file.

$insert takes the value of $header if the first line of inFile is being read, else the value of $value. The fields are split, the new column value is spliced into place, then the new line is printed.

Hope this helps!

相关阅读:
Top