Perl Code to change file delimiter (passed as argument) to bar delimiter

Hi,

Extremely new to Perl scripting, but need a quick fix without using TEXT::CSV

I need to read in a file, pass any delimiter as an argument, and convert it to bar delimited on the output. In addition, enclose fields within double quotes in case of any embedded delimiters.

Any help would be greatly appreciated, thanks

Here's a recipe from Perl cookbook (the sub routine parse_csv can be found in it):

#! /usr/bin/perl
use warnings;
use strict;

my $d = $ARGV[0];

sub parse_csv {
  my $text = shift;
  my @columns = ();
  push(@columns ,$+) while $text =~ m{
    "([^\"\\]*(?:\\.[^\"\\]*)*)",?
      | ([^,]+),?
      | ,
    }gx;
  push(@columns ,undef) if substr($text, -1,1) eq ',';
  return @columns;
}

my @cols = ();
my $line = undef;

open I, "< file.txt";
while ($line = <I>) {
    chomp($line);
    @cols = parse_csv($line);
    print join($d, @cols), "\n";
}
close I;
[user@host ~]$ cat file.txt
a,b,c,"d,e,f",g,h
a,b,c,"d,e,f",g,h
a,b,c,"d,e,f",g,h
[user@host ~]$ ./test.pl '|'
a|b|c|d,e,f|g|h
a|b|c|d,e,f|g|h
a|b|c|d,e,f|g|h
[user@host ~]$
1 Like

Thanks, I will check it out!