How to end the `i` command in GNU sed?

326 Views Asked by At

I'm trying to use sed to make several substitutions and insertions of an input string.

However, I recently noticed that the insert command i doesn't terminate on ; like others, and instead prints the rest of the string.

$ sed "s/^foo/bar/; 1i foo foo foo; s/foo$/baz/;"

When running that command on the following input,

foo bar baz

I get the following incorrect output.

foo foo foo; s/foo$/baz/;
bar bar baz

What's the correct way to terminate that command?

1

There are 1 best solutions below

0
Wiktor Stribiżew On BEST ANSWER

You may use multiple -e separated queries in a single command:

sed -e 's/^foo/bar/' -e '1i foo foo foo' -e 's/foo$/baz/' <<< "foo bar baz"

See the online sed demo. Output:

foo foo foo
bar bar baz