Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 770
Martín Fixman Avatar asked Jan 24 '26 22:01

Martín Fixman


1 Answers

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
like image 132
Wiktor Stribiżew Avatar answered Jan 27 '26 14:01

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!