macossedbsd

How to use insert function in BSD/macOS sed


I'm trying to figure out how the i command in BSD/macOS sed works. From the man page, it looks like sed -e '/^/i\' -e $'\t' <<< a should print: <tab>a (where <tab> is a tab char, I just want it to be visually clear).

However it just prints a.

So how does one use the i function in BSD/macOS sed?


Solution

  • The lines to be inserted by an i command are part of the command. You cannot break one command across multiple expressions. Your i command ends at the end of the expression, and therefore expresses inserting zero lines. The second expression contains only whitespace, so it in fact expresses no commands at all.

    Multiline commands such as i are more clearly expressed in a sed script stored in a file, but if you want to do it using command-line arguments only then this would do it:

    sed -e '/^/i\
    '$'\t' <<< a
    

    Note, however, that i inserts complete lines, so the result is

    <tab>
    a
    

    (two lines).

    For the result you say you want, an s command would be both more appropriate and easier to write:

    sed -e s/^/$'\t'/ <<< a
    

    Note also that /^/ matches the beginning of every line. For that, you don't need a pattern at all. The command alone will do, as in the expression above.