remove space in front or end of each field

Hi,

I have a txt file called a.txt which contain over 10,000 records and I would like to remove space before comma or after comma....like below:

The input (for example two record 00001,00002):
00001,client,card limited ,02292,N ,162:41 , 192, 94.589000, 0.000000, 94.589000, 0.000000,0 , 0, 0.000000, 0.000000, 0.000000, 0.000000,162:41 , 192, 94.589000, 0.000000, 94.589000, 0.000000,SIG ,SIN
00002,client2,hello Corporation Limited ,02507,N ,1594:23 , 193, 332.890000, 0.000000, 332.890000, 0.000000,0 , 0, 0.000000, 0.000000, 0.000000, 0.000000,1594:23 , 193, 332.890000, 0.000000, 332.890000, 0.000000,AUS ,AUD

output:
00001,client,card limited,02292,N,162:41,192,94.589000,0.000000,94.589000, 0.000000,0,0,0.000000,0.000000,0.000000,0.000000,162:41,192,94.589000, 0.000000,94.589000,0.000000,SIG,SIN
00002,client2,hello Corporation Limited,02507,N,1594:23,193,332.890000,0.000000,332.890000,0.000000,0 ,0,0.000000,0.000000,0.000000,0.000000,1594:23,193,332.890000,0.000000,332.890000,0.000000,AUS,AUD

condition:

  • the 3nd field is a company name which may have space between each word. However, I just need to delete space at front and end split by ","
  • the last field like record no#1 "SIN" may contain a few space after "SIN", I also need to delete it as well.

Please help and thanks!!!!!

Hi,
You can achieve this using sed,
cat filename | sed 's/ ,/,/g' | sed 's/, /,/g' | sed 's/ $//g'

filename is the input file name.
Thanks
Raghuram

Your statement is not work..nothing change. I think the sed is not in my system.

To remove multiple leading/trailing spaces...

sed 's;^ *;;;s; *, *;,;g;s; *$;;' a.txt > b.txt

Give a try on this..

awk -F"," '{ s=""; for(i=4;i<=NF;i++) { if (i==4) {s=$i; } else {s = s","$i;} } gsub(/ /,"",s); sub(/\(.*\) ,/",",$3); print $1","$2","$3","s; }' filename

great! It's work..can you explain to me the statment? Thx!!

it will become clearer like this:

sed 's/^ *//;s/ *, */,/g;s/ *$//' file