How to Replace Spaces with Commas in the Linux Console (sed, tr, awk)
Processing logs and other text data is handy with scripts right in the Linux console. With sed, awk and regular expressions you can almost work miracles
A common task is to replace spaces with commas, for example to turn a line into CSV.

In short: sed 's/ /,/g' file replaces all spaces with commas. Without g only the first space on each line is replaced.
Replace the first space
sed 's/\s/,/' test.txt red,blue green black
\s matches any whitespace character (a space or a tab).
Replace all spaces
Add the g (global) flag:
sed 's/\s/,/g' test.txt red,blue,green,black
Several spaces in a row — one comma
If words are sometimes separated by two or three spaces or tabs, replace the whole group at once:
sed -E 's/\s+/,/g' test.txt
Other ways
tr ' ' ',' < test.txt— the simplest way to replace each space with a comma;awk -v OFS=',' '{$1=$1; print}' test.txt— replaces any runs of spaces with a comma and trims spaces at the start and end of the line;sed -i 's/ /,/g' test.txt— edits the file itself (without-ithe result is only printed). Make a copy of the file before using-i.
That simple!