0

I want to find repeated spaces (more than one) and replace them with one space. I tried:

sed -e 's/ []+/ /g' myfile.txt > myfile2.txt

This resulted in an empty file. Why? and how to achieve my goal?

1

Your command errors out: sed: -e expression #1, char 10: unterminated 's' command so possibly because there is no standard output generated.

Try sed -e 's/ \+/ /g' myfile.txt > myfile2.txt

Also: https://stackoverflow.com/questions/22939323/sed-command-to-replace-multiple-spaces-into-single-spaces

0

In standard sed, to search for one or more SPC characters, the syntax is:

sed 's/ \{1,\}/ /g'

Or

sed 's/  */ /g'

(that's two spaces before the star). Or to make it more legible:

sed 's/[ ][ ]*/ /g'

Once -E (for extended regular expressions) is added to the standard (which should happen in the next major POSIX release, many implementations already support it), you could also do:

sed -E 's/ +/ /g'

Some sed implementations also understand \+ with basic regex (without -E) as an alias for \{1,\}.

But here, you could just use tr instead:

tr -s ' ' < file.in > file.out

To squeeze the spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.