Score:0

Replace sequence of a charachter with another one

in flag

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.

Score:5
hr flag

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
Score:0
gi flag

Using sed

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

you will have

391KB,7.48MB,7.86MB

Or alternatively, if the separator is space and you can merge multiple spaces, you can use also the great Miller in this way

echo '                     391KB     7.48MB     7.86MB' | mlr --n2c --ifs ' ' -N --repifs cat

to have

391KB,7.48MB,7.86MB

Starting from a file

<input mlr --n2c --ifs ' ' -N --repifs cat >output.csv
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.