0

my code example

var='
    content="
            line1:'$1'
            line2:'$2'
            "
    for lines in ${content[@]}
    do
      echo print $lines
    done
    '

the above content I want to insert into a file after a particular string.

I am using the following command but it doesn't work for me as it inserts only the strings into the file.

what I was trying:

sed -i '/pattern/a\ Hello world' destination.sh

how I want:

sed -i '/pattern/a\ '`echo "$var"`'' destination.sh
αғsнιη
  • 41,407
Gopi
  • 1
  • $1 and $2 will be replaced when you assign var, is this what you want? – pLumo Mar 09 '21 at 07:51
  • Could you put that long string into a file and then append using sed's r command (instead of a). This gets around all the quoting you may have to do in the shell. – Daniel Junglas Mar 09 '21 at 07:53

2 Answers2

2

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)?).

Kusalananda
  • 333,661
0

Using here-doc with and a temporary file:

cat > tmp.txt << EOF
    content="
            line1:'\$1'
            line2:'\$2'
            "
    for lines in \${content[@]}
    do
      echo print \$lines
    done
EOF

sed "/pattern/r tmp.txt" file rm tmp.txt