The first line is variable ann hold quite complicated value. The reason I use the second line is because I don't want to change anything in the third line col1content. To change replacement, I just need to change second line to other variable.

ann="<?php echo '<h2>'.views_get_view('frprev_ann')->get_title().'<\/h2>'; echo views_embed_view('frprev_ann'); ?>"
col1content=`echo $ann`
sed -i 's/r'$rownum'c1content/'$col1content'/g' templates/page--front.tpl.php

But when above command has been run, it result in error:

sed: -e expression #1, char 19: unterminated `s' command

If I change the first line to be ann="testtext", everything running smoothly. And when change first line to be ann="<?first second", it fails. using backslash also cannot help me.

  • why you do you want your code to contain `col1content=echo $ann` in the second line instead of col1content=$ann – miracle173 Oct 10 '12 at 2:07
sed -i 's/r'$rownum'c1content/'"$col1content"'/g' templates/page--front.tpl.php

You can't reliably pass text to sed like this. In the replacement text, you need to quote \, & and the s delimiter (usually /) by adding a backslash before them. In the regex part, you need to quote \[.*^$ and the delimiter.

In addition, you've left the value of the variable to be further expanded by the shell. Always use double quotes around variable substitutions, i.e. "$foo", not $foo. Without double quotes, the value is interpreted as a whitespace-delimited list of glob patterns; whitespace and \[?* are expanded.

If you don't want to change the way the script works, quote everything properly:

ann="<?php echo '<h2>'.views_get_view('frprev_ann')->get_title().'</h2>'; echo views_embed_view('frprev_ann'); ?>"
col1content=$(echo "$ann" | sed 's/[\\\/&]/\\&/g')
sed -i "s/r${rownum}c1content/${col1content}/g" templates/page--front.tpl.php

Alternatively, use awk or perl, which can read an environment variable from within the script.

ann="<?php echo '<h2>'.views_get_view('frprev_ann')->get_title().'</h2>'; echo views_embed_view('frprev_ann'); ?>"
awk -v ann="$ann" -v rownum="$rownum" '
    BEGIN {pattern = "r" rownum "c1content"; }
    1 {gsub(pattern, ann); print}
' templates/page--front.tpl.php >templates/page--front.tpl.php.new
mv templates/page--front.tpl.php.new templates/page--front.tpl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.