0

This question already has an answer here:

Example input:

A0021,,Outside state ambulance serv,I,,0,0,,
A4217,,"Sterile water/saline, 500 ml",X,,
A4672,,"Drainage ext line, dialysis",X,,

Example output after first sed command

sed -i 's/("[^,])[,]([^"]")/\1\2/g' file.csv :

A0021,,Outside state ambulance serv,I,,0,0,,
A4217,,"Sterile water/saline, 500 ml",X,,
A4672,,"Drainage ext line dialysis",X,,

Desired output after the last command:

A0021,,,I,,0,0,,
A4217,,,X,,
A4672,,,X,,

The third column has been giving me issues in a project and the easiest solution is to simply delete it, as it is not necessary. The commas should remain, it should just have empty contents.

I was thinking that I would need to develop a sed command to remove the commas contained within quotes before the command to delete the third column, as I would imagine that the easiest way to do this would be to count the commas and then delete everything between the 2nd and 3rd comma.

this is the sed command I am using the delete the commas inside of the quotes before I proceed with clearing the 3rd column's contents

marked as duplicate by Kusalananda, Jeff Schaller, GAD3R, sam, thrig Jan 30 '17 at 22:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Try to read this. In your case I would use: awk -F, 'sub($3,"")' OFS=, file.csv – andreatsh Jan 9 '17 at 22:51
  • But I suggest you to post also your expected output and the command(s) you've tried so far. – andreatsh Jan 9 '17 at 22:54
  • @andreatsh that wouldn't work since the third field contains quoted commas and awk won't see that. If that's the only field with quotes, you might try awk -F'"' '{$2=""}' which will delete everything between the quotes, whether there are commas or not. – MAP Jan 10 '17 at 3:37
  • @andreatsh I have went ahead and added the sed command I will be using to clear the comma contained quotes. I will test the awk provided to see if that does what I expect. Thank you – Patrick Carey Jan 10 '17 at 15:48
0

Something like this will do the trick:

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

use Text::CSV;

my $csv = Text::CSV->new( { binary => 1, eol => "\n" } );

open( my $input, '<', 'test3.csv' ) or die $!;

while ( my $row = $csv->getline($input) ) {
   $row->[2] = "";
   $csv -> print( \*STDOUT, $row );
}

(You probably want to open an output file and print to that instead though).

Not the answer you're looking for? Browse other questions tagged or ask your own question.