I'd like to perform multiple inserts/appends in a single sed command that is portable.
In GNU sed, I can do something like:
sed -e '1i hi' -e '$a bye' <(seq 1 10)
I've the found the following works, but I'm not sure if it's the correct/best way to handle it in Posix compliant sed:
sed --posix '1{x;s/$/hi/;G};//h;${x;s/$/\nbye/}' <(seq 1 10)
--or--
sed --posix '1{x;s/$/hi/;G};${s/$/\nbye/}' <(seq 1 10)
I've not seen anyone really discuss how to delete the hold space, took a guess - is this the best way to effect this in all posix compliant seds?
Update: since \n
on RHS is not portable, looks like it's going to take multi-lines:
sed --posix '1{x;s/$/hi/;G};${s/$/\
> bye/}' <(seq 1 10)
Update: Ok, guess I found a way to add newline by grabbing it in a hold on the LHS - kinda ugly though:
sed '1{G;s/\(.\)\(\n\)/hi\2\1/;};${G;s/\(.\)\(\n\)/\1\2bye/;}' <(seq 1 10)
or this, a little better:
sed '1{G;s/\([^\n]*\)\(\n\)/hi\2\1/;};${G;s/\(\n\)/\1bye/;}' <(seq 1 10)
Answer - Settled on Potong's parameter expansion version, looks posix compliant:
sed --posix $'1i\\hi\n;$a\\bye' <(seq 1 10)
One liner is preferred
This might work for you (GNU sed & bash):
sed $'1i\\hi\n$a\\bye' file
or
sed '1G;1s/\(.*\)\(.\)/hi\2\1/;$G;$s/$/bye/' file
or
sed '1h;1s/.*/hi/p;1g;$a\bye' file
or
sed 'H;1h;$!d;s/.*/hi/;G;a\bye' file
or
sed '1{x;s/^/hi/p;x};${p;s/.*/bye/}' file