Is the use of sed’s “a” command to prefix a line portable

portabilityposixsed

I noticed the following interesting behavior:

$ printf '%s\n' line{1..2} | sed $'1a\\\nPREFIX'
line1
PREFIXline2
$ 

Interestingly, this behavior is only possible for the last command in a Sed script, as to put another command afterwards requires a newline.

It also works with the insert command:

$ printf '%s\n' line{1..2} | sed $'1i\\\nPREFIX'
PREFIXline1
line2
$ 

Can this behavior be depended upon?

I don't see it mentioned one way or another in the POSIX specs for Sed. It just says that the text may consist of one or more lines. (If a line doesn't end in a newline character, is it still a line?)

It also works with multiple line insertions:

$ printf '%s\n' line{1..2} | sed $'1a\\\n ****/\n1i\\\n/****\\\n * '
/****
* line1
****/
line2
$ 

Best Answer

I just tested with a different Sed and found this is a peculiarity of BSD Sed; GNU Sed gives different results best illustrated with the output of the last command given above:

$ printf '%s\n' line{1..2} | sed $'1a\\\n ****/\n1i\\\n/****\\\n * '
/****
 *
line1
 ****/
line2
$
Related Question