Search code examples
shellsedposixwhitespace

BSD sed ignores the leading spaces in the text for a\ command


Leading spaces are preserved in echo command. Take this script for example:

echo 'abc
    def'

Output:

$ sh foo.sh 
abc
    def

But leading space in sed text for a\ command is not preserved with the BSD sed that comes with macOS. Take this script:

echo abc | sed '/abc/a\
    def
'

Output with BSD sed on macOS:

$ sh foo.sh 
abc
def

Output with GNU sed on Linux:

$ sh foo.sh
abc
    def

I am able to resolve this issue on macOS and preserve the leading spaces like this:

echo abc | sed '/abc/a\
\ \ \ \ def
'

Output:

$ sh foo.sh 
abc
    def

Where is the behavior of ignoring leading spaces in the text for a\ command specified in POSIX documentation of sed?

I could not find anything in the documentation that says this behavior of ignoring leading spaces in the text for a\ is is correct. Can you see anything in the documentation that says this behavior is correct?


Solution

  • It looks as though you were right. To the extent of the specific observation you have made, the behavior of your sed would be nonconforming.

    Indeed, POSIX (as you have linked it) says:

    Editing commands other than {...}, a, b, c, i, r, t, w, :, and # can be followed by a <semicolon>, optional <blank> characters, and another editing command. However, when an s editing command is used with the w flag, following it with another command in this manner produces undefined results.

    This seems to be as close as POSIX comes to addressing the question, and—by excepting the a command from the stipulation—it seems to be admitting that which was already implied. It seems to be admitting that blanks are significant for a.

    My answer is not wholly conclusive, of course, but you would seem to have the weight of the evidence on your side.