Replace comma by space for specified field in record

Hi,

i want to replace comma by space for specified field in record, i mean i want to replace the commas in the 4th field by space. and rest all is same throught the record.

the record is

16458,99,001,"RIMOUSKI, QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER, QC",418,"N",5,MST,MDT,616
16458,99,003,"NEWRICHMND, QC",418,"B",7,EST,EDT,702

here i want to replace "RIMOUSKI, QC" by "RIMOUSKI QC" and for all the records of the file in the 4th position.

i can do it for file using

sed 's/,//g'

but how can i do it only for 4th field ?

try this

sed 's/,/ /4' inputfile 
awk 'BEGIN{FS=OFS="\""}{sub(",",x,$2)}1' file
sed 's/, / /g' filename 

gives

16458,99,001,"RIMOUSKI QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER QC",418,"N",5,MST,MDT,616
16458,99,003,"NEWRICHMND QC",418,"B",7,EST,EDT,702

That assumes there are no fields starting with blanks, that are one or more spaces, etc. I'm thinking the OP wants to remove commas from quoted fields, so this might be safer:

sed 's/"\([^"]*\),\([^"]*\)"/\1\2/g'

Edit: Ooops. Should have included double-quotes in parenthesis... :slight_smile:

sed 's/\("[^"]*\),\([^"]*"\)/\1\2/g'

js.

Let's simulate:

# cat file
16458,99,001,"RIMOUSKI, QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER, QC",418,"N, C",5,MST,MDT,616
16458,99,003,"NEWRICHMND QC",418,"B, C",7,EST,EDT,702

# sed 's/,/ /4' file
16458,99,001,"RIMOUSKI  QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER  QC",418,"N, C",5,MST,MDT,616
16458,99,003,"NEWRICHMND QC" 418,"B, C",7,EST,EDT,702

# awk 'BEGIN{FS=OFS="\""}{sub(",",x,$2)}1' file
16458,99,001,"RIMOUSKI QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER QC",418,"N, C",5,MST,MDT,616
16458,99,003,"NEWRICHMND QC",418,"B, C",7,EST,EDT,702

# sed 's/, / /g' file
16458,99,001,"RIMOUSKI QC",418,"N",7,EST,EDT,902
16458,99,002,"CHANDLER QC",418,"N C",5,MST,MDT,616
16458,99,003,"NEWRICHMND QC",418,"B C",7,EST,EDT,702

# sed 's/"\([^"]*\),\([^"]*\)"/\1\2/g' file
16458,99,001,RIMOUSKI QC,418,"N",7,EST,EDT,902
16458,99,002,CHANDLER QC,418,N C,5,MST,MDT,616
16458,99,003,"NEWRICHMND QC,418B, C",7,EST,EDT,702