Issue with Pattern Matching in Unix

Hi,

I am trying to replace a specific column values in a csv file with double quotes.

Example:

SNO,NAME,ZIPCODE,RANK,CARE_OF
1,Robert,74538,12,RICHARD JOHNSON, P.C
2,Sam,07564,13,% R.S MIKE, V.K.S
3,Kim, Ed,12345,14,@90 KMS, %TK

Desired Output:

SNO,NAME,ZIPCODE,RANK,CARE_OF
1,Robert Ken,74538,12,"RICHARD JOHNSON, P.C"
2,Sam Mik,"07564",13,"% R.S MIKE, V.K.S"
3,"Kim, Ed",12345,14,"@90 KMS, %TK"

I would like to replace the zipcode value with double quotes when I find a leading zeros for the zipcode. Also, I would like to replace the name in double quotes when I found a comma with in the name.
Also, I would like to replace the CARE_OF value with double quotes when I found a comma with in this column value.

The following command is working fine for Name and Zipcode column values, please advice on CARE_OF column value.

sed -e 's/,\(0[0-9]*\)/,\"\1\"/g'  -e 's/,\([ 0-9A-Za-z]*, [  0-9A-Za-z]*\),/,\"\1\",/g' -e 's/,\([ 0-9A-Za-z]*, [ 0-9A-Za-z]*\),/,\"\1\",/g' inputFile.csv > outputFile.csv

Please throw your ideas :slight_smile:

Thanks,
moris.

% gawk -F',' ' {

if(NF==5) { if($3 ~ /^0/) { $3 = "\"" $3 "\"" } print $0 }
else {
    sno=$1

    if($3 !~ /^[0-9]*$/)  {

        name="\"" $2 "," $3 "\""; zip=$4;

        if($(NF-1) !~ /^[0-9]*$/)  {

             care_of="\"" $(NF-1) "," $(NF) "\""; rank=$(NF-2);

        } else { care_of=$6;rank=$5; }

    } else {

         if($3 ~ /^0/) { $3 = "\"" $3 "\"" }
         name=$2; zip=$3;
         if($(NF-1) !~ /^[0-9]*$/)  { care_of="\"" $(NF-1) "," $(NF) "\""; rank=$(NF-2); } else { care_of=$5;rank=$4; }
    }
    if(zip ~ /^0/) { zip = "\"" zip "\"" }
    print sno "," name "," zip "," rank "," care_of
}

} ' inputFile.csv > outputFile.csv

% cat *csv
SNO,NAME,ZIPCODE,RANK,CARE_OF
1,Robert Ken,74538,12,RICHARD JOHNSON, P.C
2,Sam Mik,07564,13,% R.S MIKE, V.K.S
3,Kim, Ed,12345,14,@90 KMS, %TK
SNO,NAME,ZIPCODE,RANK,CARE_OF
1,Robert Ken,74538,12,"RICHARD JOHNSON, P.C"
2,Sam Mik,"07564",13,"% R.S MIKE, V.K.S"
3,"Kim, Ed",12345,14,"@90 KMS, %TK"

Cheers,

coding-school