The question asks explicitly about sed, and it's a very valid question about sed regexp syntax.
But in case the underlying question is about replacing spaces by
_ really, here is an alternative answer using the "right tool for the job" for translating characters, which is
tr abc 123 replaces the chars of the first list with the corresponding chars in the second. Thus,
tr ' ' _ replaces space by underscore.
$ echo ' 1 2 3 ' | tr ' ' _
To show the more general case, including various kinds of whitespace like your example,
here is the output for only translating the normal space character
' ' for comparison:
echo ' 1 2 3 x\ny\tz' | tr ' ' _
And here is the output when translating all characters of the class :space: to
echo ' 1 2 3 x\ny\tz' | tr '[:space:]' _
(Note there is no newline at the end of the output - and there is a
_ after the
This can be written explicitly as
tr ' \t\n' _, which is the short form of
tr ' \t\n' ___.
$ echo ' 1 2 3 x\ny\tz' | tr ' \t\n' _