I want append some lines through a bash script with sed. The script works but the output is wrong.

sed '/g id=\"..\"/a style=\"fill:$LINEB;\"' file.txt > foo.txt

I get <g id="ai" style="fill:$LINEB;"> instead of <g id="ai" style="fill:word;">

Even if I use all kinds of parenthesis.

  • It's not substituion. It's append /a. Nov 29, 2015 at 21:58

2 Answers 2


You can't embed a variable inside single-quotes. You could:

  1. use double-quotes around the entire sed script, and backslash-escape all the double-quotes inside it.

  2. end the single-quoted string with a ', double-quote-the variable, and then re-start the single-quoted string again:

sed '/g id=\"..\"/a style=\"fill:'"$LINEB"';\"' file.txt > foo.txt
  • 1
    Yeah but I get this error sed: -e expression #1, char 66: extra characters after command Nov 29, 2015 at 21:55
  • That would be because your sed command is invalid. I'm unable to fix that because i have no idea what you're trying to do with sed. The technique for switching between single and double-quotes will work even better with a valid sed command. Also remember that your variables have to be properly escaped if they are to be successfully embedded in a sed command.
    – cas
    Nov 29, 2015 at 22:00

First, you need to take care that $LINEB is properly prepared for a sed append command:

sed '/<\([^"<>]*\("[^"]*"\)* \)*g id="[^"][^"]"/a\'"$(echo;#"'
     printf 'style="fill:"%s"\n' "$LINEB" |
     sed 'H;1h;$!d;s/\\/&&/g;s/\n/\\&/g')
"    <infile >outfile

It might also be easier to locate the appended text in another file that you can then read in whenever appropriate:

printf 'style="fill:%s"\n' "$LINEB" >/tmp/LINEB
sed '/<\([^"<>]*\("[^"]*"\)* \)*g id="[^"][^"]"/r /tmp/LINEB' <infile >outfile
rm /tmp/LINEB

This requires no escaping.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .