I was under the impression from the POSIX specs for sed
that it is necessary to left-align the text on the line following the i\
command, unless you want leading whitespace in the output.
A quick test on my Mac (using BSD sed) shows that perhaps this is not necessary:
$ cat test.sed
#!/bin/sed -f
i\
This line starts with spaces.
$ echo some text | sed -f test.sed
This line starts with spaces.
some text
$
However, I can't seem to find this documented anywhere. It's not in the POSIX specs, and it's not even in sed
's man page on my system.
Can I rely on this behavior in sed
scripts which I want to be portable? How portable is it?
(Is it documented anywhere?)
(Bonus question: Is it even possible to force sed
to insert whitespace at the beginning of a fixed line passed to i\
?)
Best Answer
No but your script will be portable as long as you escape any leading blank. Why ? Because some
sed
s strip blank characters from text lines and the only way to avoid that is to escape the leading blank, as these manual pages dating back from the last century explain: 1, 2, 3The same goes for
BSD
sed
(OSX
just copied the code, it's not their extension) and if you check the archives and read theman
page fromBSD 2.11
it's pretty clear:Now, where is this documented in the POSIX spec ? It only says
and if you scroll down under RATIONALE it says
Since the part with "backslashes may be used to" was not included in that quote, the remaining phrase "protect initial blanks..." doesn't make any sense...1
Anyway, to sum up: some implementations did (and some still do) strip blanks from text lines. However, since the POSIX spec to which all implementations should comply says
we can conclude that the portable way to indent the lines in the text-to-be-inserted is by escaping the leading blank on each of those lines.
1: I also don't understand why
OSX
/BSD
people have changed the entire paragraph in theman
page without altering the source code - you get the same behavior as before but the man section that documents this stuff is no longer there.