#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Find and Replace File Delimiter


    Hi all!

    I need to pass the file delimiter as an argument, read through the file replacing the passed delimiter with Bar delimiter. Also need to enclose fields in double quotes where bar delimiter is already embedded.Any advice would be greatly appreciated, thanks!

    JPB
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,954
    Rep Power
    1225
    Take a look at Text::CSV - comma-separated values manipulator (using XS or PurePerl)

    The module lets you specify the delimiter (field separator), so it doesn't have to be a comma as the name implies.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    10
    Rep Power
    0
    As FishMonger suggested, you could use Text::CSV, (or Text::CSV_XS), to read the csv file and replace the comma with a bar/pipe. Text::CSV will quote any fields that contain the delimiter when printing out. Here is a sample program along with the original comma separated values and the file created with the bar separated values. Notice that fields with an included bar are quoted.
    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    use Text::CSV_XS;
    
    my $parser = Text::CSV_XS->new({binary => 1, sep_char => ','});
    my $writer = Text::CSV_XS->new({binary => 1, sep_char => '|', eol => "\n"});
    
    my $read = 'c.csv';
    my $write = 'junk.csv';
    open my $in, "<", $read or die "$read: $!";
    open my $out, ">", $write or die "$write $!";
    
    while (my $row = $parser->getline ($in)) {
        $writer->print($out, $row);
    }
    
    close $in or die $!;
    close $out or die $!;
    Input and output files:
    Code:
    C:\Old_Data\perlp>type c.csv
     ,A,B,C
    w|hite,1,0,1
    b|lack,1,0,1
    b|rown,3,1,4
    r|ed,1,1,0
    g|rey,1,5,3
    
    C:\Old_Data\perlp>type junk.csv
    " "|A|B|C
    "w|hite"|1|0|1
    "b|lack"|1|0|1
    "b|rown"|3|1|4
    "r|ed"|1|1|0
    "g|rey"|1|5|3
    
    C:\Old_Data\perlp>

IMN logo majestic logo threadwatch logo seochat tools logo