Search code examples
shelldelimiter

need a shell script to change the comma delimiter to a pipe delimeter


My input looks like "$130.00","$2,200.00","$1,230.63" and so on My question is how can I go about changing the comma delimiter to a | delimiter without getting rid of the comma in the actual input. Just to clarify this input is in a csv file with 40 columns and 9500 rows. I want my output to look like

"$130.00"|"$2,200.00"|"$1,230.63"

Solution

  • To do this reliably, you have to use states to keep track of wether you are inside a string or not. The following perl script should work:

    #!/usr/bin/perl -w
    use strict;
    use warnings;
    
    my $state_outside_string = 0;
    my $state_inside_string  = 1;
    
    my $state = $state_outside_string;
    
    while (my $line = <>) {
        my @chars = split(//,$line);
        foreach my $char (@chars) {
            if ($char eq '"') {
                if ($state == $state_outside_string) {
                    $state = $state_inside_string;
                } else {
                    $state = $state_outside_string;
                }
            } elsif ($char eq ',') {
                if ($state == $state_outside_string) {
                    print '|';
                    next;
                }
            }
            print $char;
        }
    }