Each line ends with a newline, and newline is a form of whitespace (/\s/). Either chomp off the line endings and add them back when you output, or be more selective in what you replace (i.e. match / /, /\t/ or /[ \t]/ instead of /\s/).
Update: Sorry, this is effectively a duplicate of the earlier post which I somehow missed.
In reply to Re: replace middle spaces with commas
by ikegami
in thread replace middle spaces and write to another file
by sufi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |