Assuming the text only needs to be inserted once, I would probably not use the a
editing command here, but r
to read from a file:
cat <<END_CODE | sed '/pattern/r /dev/stdin' destination.sh
content=( line1:${1@Q} line2:${2@Q} )
for lines in "${content[@]}"; do
echo print "$lines"
done
Above loop shorter: printf 'print %s\n' "${content[@]}"
END_CODE
(Note corrected shell code in text block, assuming $1
and $2
should be expanded in the code that is inserted, and that the other variables shouldn't be expanded until the inserted code is run.)
Or, if you want to keep your var
variable:
printf '%s\n' "$var" | sed '/pattern/r /dev/stdin' destination.sh
If you need to insert the code several times, write the text to a real file and read that file with r
in the same way:
sed '/pattern/r mycode' destination.sh
The issue with your code is that you are trying to insert the variable's value into the sed
editing code, which is a single quoted string. Variables are not expanded inside single quoted strings. You could switch to using double quotes, but then you have the issue of making sure that your inserted data does not break your editing script's syntax (for example, if any line apart from the last isn't ending with \
). It would therefore be safer and more convinient to use r
in place of a
.
If you are on macOS, be sure to upgrade your bash
from the default native one to a more current release. You may do that with the Homebrew package manager. Also note that sed -i
works differently on macOS than on e.g. Linux (see How can I achieve portability with sed -i (in-place editing)?).
var
, is this what you want? – pLumo Mar 09 '21 at 07:51r
command (instead ofa
). This gets around all the quoting you may have to do in the shell. – Daniel Junglas Mar 09 '21 at 07:53