How to keep newline intact in a sed command used in Makefile (POSIX)?

Parameter Expansion with Suffix Removal in sed

Here is a solution that puts <newline>x (i.e., newline followed by the character x) in a variable and then uses this variable in the sed command. While using this variable, we use shell parameter expansion to get rid of the x suffix, so that we are only left with a newline.

all:
    NX=$$(printf '\nx'); printf 'foo\nbaz\n' | sed "/foo/a\\$${NX%x}bar$${NX%x}"

The value of NX is <newline>x, so ${NX%x} evaluates to just <newline>. Here is the output:

$ make
NX=$(printf '\nx'); printf 'foo\nbaz\n' | sed "/foo/a\\${NX%x}bar${NX%x}"
foo
bar
baz

Simplifying Parameter Expansion in sed with make Macros

We can simplify the usage of the previous solution with make macros. We put all the unwieldy parts into macros. Then we expand those macros in the shell commands. Here is an example:

NX = NX=$$(printf '\nx')
NL = $${NX%x}

all:
    $(NX); printf 'foo\nbaz\n' | sed "/foo/a\\$(NL)bar$(NL)"

Here is the output:

$ make
NX=$(printf '\nx'); printf 'foo\nbaz\n' | sed "/foo/a\\${NX%x}bar${NX%x}"
foo
bar
baz

Parameter Expansion with Suffix Removal Before sed

Here is another possible solution on similar lines. Instead of writing the unwiedly syntax of ${NX%x} within the sed command twice, it is simplified by assigning ${NX%x} itself to another shell variable named NL and ${NL} is used instead in the sed command.

all:
    NX=$$(printf '\nx'); NL=$${NX%x}; printf 'foo\nbaz\n' | sed "/foo/a\\$${NL}bar$${NL}"

Here is the output:

$ make
NX=$(printf '\nx'); NL=${NX%x}; printf 'foo\nbaz\n' | sed "/foo/a\\${NL}bar${NL}"
foo
bar
baz

Simplifying Parameter Expansion Before sed with make Macros

The usage of the above solution can be simplified further with make macros as follows:

NX = NX=$$(printf '\nx'); NL=$${NX%x}
NL = $${NL}

all:
     $(NX); printf 'foo\nbaz\n' | sed "/foo/a\\$(NL)bar$(NL)"

Here is the output:

$ make
NX=$(printf '\nx'); NL=${NX%x}; printf 'foo\nbaz\n' | sed "/foo/a\\${NL}bar${NL}"
foo
bar
baz