1

It must be really easy, but somehow I don't get it… I want to process an HTML-file via a bash script and insert an HTML-String into a certain node:

org.html: <div id="wrapper"></div>

MYTEXT=$(phantomjs capture.js www.somesite.com)
# MYTEXT will look something like this:
# <div id="test" style="top: -1.9%;">Something</div>

sed -i "s/\<div id=\"wrapper\"\>/\<div id=\"wrapper\"\>$MYTEXT/" org.html

I always get this error: bad flag in substitute command: 'd' which is probably because sed interprets the content of $MYTEXT as a pattern as well – which is not what I want…

By the way: Duplicating \<div id=\"wrapper\"\> is probably also not necessary?

AvL
  • 3,083
  • 1
  • 28
  • 39
  • 1
    Here is a related question: http://stackoverflow.com/q/584894/951890 – Vaughn Cato Nov 12 '13 at 15:17
  • 1
    "`By the way: Duplicating \
    is probably also not necessary?`": Yes you can use backreferencing with `\1`; You need to enclose `\
    – anishsane Nov 12 '13 at 16:24
  • Well, I did try this: `sed "s|(\
    )|\1$MYTEXT|" test.html` but I get this error in return: `\1 not defined in the RE`
    – AvL Nov 12 '13 at 16:42
  • Never mind – I am on a Mac which uses `BSD sed`. `\1` has to be replaced by `&`: `sed "s|(\
    )|&$MYTEXT|" test.html`
    – AvL Nov 13 '13 at 12:05

1 Answers1

2

It seems the / in $MYTEXT's </div> part is interpreted indeed as the final / in the sed command. You can choose another delimiter, which does not appear in $MYTEXT, for instance:

sed -i "s|\<div id=\"wrapper\"\>|\<div id=\"wrapper\"\>$MYTEXT|" org.html
damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • This looks good! Which characters are allowed as delimiters? I need to choose a really rare one, because I don't know `$MYTEXT`s content. Using e.g. `†` leads to `error: illegal byte sequence` – AvL Nov 12 '13 at 15:27
  • 2
    Any character is permitted, even a control character such as Control-A or Control-G. – Jonathan Leffler Nov 12 '13 at 15:28
  • How would I insert Control-A which in my Terminal is the command to jump to the beginning of the line? – AvL Nov 12 '13 at 15:32
  • 1
    Hit Control-V before ; this will make the terminal not interpret the Control-A command – damienfrancois Nov 12 '13 at 15:34
  • 1
    Or I can make use of [ANSI-C Quoting](http://www.gnu.org/software/bash/manual/bash.html#ANSI_002dC-Quoting) and use something like `$'\001'` as a delimiter. – AvL Nov 12 '13 at 16:10