Shell Replacing spaces with newlines using SED

Try:
Code:
echo 123 abc xyz | sed 's/ /\\
/g'

See sed(1) - Sed Regular Expressions.
Code:
2.    The escape sequence \n matches a newline character embedded in the
      pattern space. You cannot, however, use a literal newline character
      in an address or in the substitute command.
 
What’s the problem? With the keyboard of course. After the two backslashes, I use the return key for the line break, and continue with /g', then comes the final return, in order to submit the command.
 
Maybe sed isn't the best tool for this job? A simple for will already split tokens on whitespace. If you must read from stdin, you could do something like this:

Code:
echo "123 abc xyz" | for i in `cat`; do echo $i; done
 
What’s the problem, with the keyboard of course. After the two backslashes, I use the return key for the line break, and continue with /g', then comes the final return, in order to submit the command.

I see... I was reediting a previous command echo 123 abc xyz | sed 's/ /\\/g' and pressed return after the two backslashes, so the cursor was over the last slash when I pressed return.

Thanks for clearing that up. But I still don't understand why '\r' doesn't work.

From https://www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1

Code:
[2addr]l
         (The letter ell.)    Write the pattern space    to the standard    output
         in    a visually unambiguous form.  This form    is as follows:

           backslash          \\
           alert          \a
           form-feed          \f
           carriage-return    \r
           tab              \t
           vertical tab          \v

         Nonprintable characters are written as three-digit    octal numbers
         (with a preceding backslash) for each byte    in the character (most
         significant byte first).  Long lines are folded, with the point
         of    folding    indicated by displaying    a backslash followed by    a new-
         line.  The    end of each line is marked with    a ``$''.
 
The answer given by obsigna is the correct answer for BSD sed.

Alternatively, there's tr:

Code:
echo 123 abc zyx | tr ' ' \\012

As for sed's l option to control output:

Code:
echo 123 abc zyz | sed -n 's/ /\^M/g;l'

It's doing what it's supposed to do and gives the following output:

Code:
123\rabc\rzyz$

The '^M' is created with the following key sequence: CTRL-V + CTRL-M.
Also note, this depends on the shell. It works on the command line using /bin/sh but not /bin/csh.
 
Back
Top