Replace sequence of a charachter with another one

I have an output from a network monitoring command and it looks like this:

                     391KB     7.48MB     7.86MB

Which have a lot of spaces first. Now I want to replace all spaces with ,.
I tried sed 's/ /,/g' input_file > output_file, But result is not exactly what I expect:

,,,,,,,,,,,,,,,,,,,,,391KB,,,,,7.48MB,,,,,7.86MB

I even tried:

sed -r 's/(.*) /\1,/; s/ //g' file.txt > output.txt

But output was like below:

391KB7.48MB,7.86MB

How can I replace the sequence of spaces with one comma?
I think it's good to mention that I want to add this data to csv file.


Solution 1:

You can match a sequence of one or more spaces portably in Basic Regular Expressions (BRE) using either * (space-space-star) or \{1,\}. In Extended Regular Expression (ERE) you can use {1,} or +. The general name for these constructs is Quantifiers.

$ echo '                     391KB     7.48MB     7.86MB' | sed 's/  */,/g'
,391KB,7.48MB,7.86MB

$ echo '                     391KB     7.48MB     7.86MB' | sed -r 's/ +/,/g'
,391KB,7.48MB,7.86MB

GNU sed allows you to use escaped \+ in BRE (as well as \? for the 0-or-1 quantifier) - as does GNU grep.

You could also use tr, with the -s (--squeeze-repeats) flag:

$ echo '                     391KB     7.48MB     7.86MB' | tr -s ' ' ,
,391KB,7.48MB,7.86MB

However if you don't want an empty initial CSV field, consider using awk - since with the default field separator it will treat contiguous whitespace as a single delimiter, and ignore leading whitespace:

$ echo '                     391KB     7.48MB     7.86MB' | awk '{$1=$1} 1' OFS=,
391KB,7.48MB,7.86MB