1

I have a file , A.csv (sep=",") :

Date And Time of Export,Batch ID,Sample Name,Well,Sample Type,Status,Interpretive Result,Action*
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565907,E11,Patient,VALID,SARS-CoV-2 Not Detected,REPORT
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565919,A10,Patient,VALID,SARS-CoV-2 Not Detected,REPORT
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565931,E01,Patient,VALID,SARS-CoV-2 Not Detected,REPORT

And I want to remove the "0" of the column 4 BUT ONLY for number [1-9] , i.e if data are "B01" I want "B1" but if data are "B10" I want it to stay "B10". So in my example it would be :

Date And Time of Export,Batch ID,Sample Name,Well,Sample Type,Status,Interpretive Result,Action*
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565907,E11,Patient,VALID,SARS-CoV-2 Not Detected,REPORT
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565919,A10,Patient,VALID,SARS-CoV-2 Not Detected,REPORT
07/15/20  19:10:03,TAQPATH-AB275013338-MOL_0003,2060565931,E1,Patient,VALID,SARS-CoV-2 Not Detected,REPORT

I've done :

awk -F ","  'BEGIN{OFS=",";} {sub("0", "", $4); print}' A.csv > B.csv

but it remove ALL the "0", can someone has an idea ?

Thanks

1
  • 1
    You could change sub("0","",$4) to sub(/0$/,RS,$4); sub(/0/,"",$4); sub(RS,0,$4) but for this particular case I prefer @Inian's approach of separating the numeric part and adding zero.
    – Ed Morton
    Jul 16, 2020 at 14:52

1 Answer 1

3

One way would be to backup the first character and replace the part containing leading 0 using sub()

awk -F "," 'BEGIN{ OFS="," } $4 ~ /^[[:alpha:]]/ { lead = substr($4, 1, 1); sub ("^[[:alpha:]]0*", lead, $4) }1' file

The initial condition $4 ~ /^[[:alpha:]]/ marks only those lines whose $4 starts with a alphabet. We only extract the first digit on those lines using substr() function and then using sub() replace from beginning and all leading zeros and substitute that pattern with the first character alone.

Another way would be to force convert the part after the first alphabet to numeric part by doing +0, which will strip off the leading zeros

awk -F "," 'BEGIN{ OFS="," } $4 ~ /^[[:alpha:]]/ && NR > 1 { $4 = substr($4, 1, 1) "" substr($4, 2)+0 }1' file
1
  • Wow it's a clever answer, thanks !
    – nstatam
    Jul 16, 2020 at 8:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .