Subject: bug#78883: backslash interpretation in 's' replacement text violates POSIX

From: Bruno Haible <[email-masked]>
Date: Mon, 23 Jun 2025 23:46:47 +0200

Hi,

When the replacement text in an 's' command contains an escape sequence
like '\n', GNU sed interprets this escape sequence, while other implementations
(OpenBSD sed, Solaris sed) do not.

How to reproduce:

$ echo foo | sed -e 's/f.*/line1\nline2/'
line1
line2

$ echo foo | POSIXLY_CORRECT=1 sed --posix -e 's/f.*/line1\nline2/'
line1
line2

Seen with GNU sed 4.9.

While OpenBSD sed, Solaris sed produce:

$ echo foo | sed -e 's/f.*/line1\nline2/'
line1nline2

POSIX [1] is ambiguous here, I would say:
Quoting:
  "For each other <backslash> encountered, the following character shall
   lose its special meaning (if any)."
but also
  "The meaning of an unescaped <backslash> immediately followed by any
   character other than '&', <backslash>, a digit, <newline>, or the
   delimiter character used for this command, is unspecified."

So the interpretation of escape sequences looks like a GNU extension.

By the description of the '--posix' option ("In order to simplify
writing portable scripts"), the --posix option should turn off this
interpretation. Or, better, emit a diagnostic.

Bruno

[1] https://pubs.opengroup.org/onlinepubs/9799919799/utilities/sed.html