0

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?

1
  • Any time you're using constructs other than s, g, and p (with -n) in sed, you should seriously consider using awk instead for simplicty, clarity, consistency, portability, etc. If you want to print a tab at the start of each line it's awk '{print "\t" $0}' using any awk in any shell on every Unix box. Commented Jun 7 at 11:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I must have gotten myself confused with another tool where splitting an expression across multiple -e flags injects a newline between them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.