0

I have 2 html files.

  • index.html in a folder called "main"
  • other.html in a folder called "other"

index.html has the below code:

<h1>My first story</h1>
<p>The pen was blue.</p>

other.html had the below code:

<p>The pen was black.</p>

I want to replace the paragraph content in "index.html" with the entire content of other.html so that index.html will give out the below result:

<h1>My first story</h1>
<p>The pen was red.</p>

I tried using the terminal command cd main && sed -e "s_<p>The pen was blue.</p>_$(cd ../other && sed 's:/:\\/:g' other.html)_" index.html but I got the error message "bash: cd: main: No such file or directory". Even when I tried putting them in the same directory for the purpose of testing it did not work. But I need them in separate folders.

Update: I fixed the issue of accessing files in different directories by using the command sed -e "s_<p>The pen was blue.</p>_$(sed 's:/:\\/:g' other/other.html)_" main/index.html but now I get the error message "sed: -e expression #1, char 54: unterminated `s' command"

How do I make it copy the contents of the 2nd file into the 1st file?

niyojet344
  • 43
  • 2
  • 9
  • If `cd main` then nothing else will work so debug that first then ask about the rest if you need help. – Ed Morton Dec 27 '21 at 20:13
  • @EdMorton I debugged the "cd main" part but it is still showing an error cause it can;t recognize the contents of the 2nd file. – niyojet344 Dec 27 '21 at 20:50
  • Does it _have to_ be sed? Why not use python? | @edit `python -c 'stuff'` and `perl -pe 'stuff'` is also a "command line". Basically every command is command line - `echo "int main() { }" | gcc -xc - && ./a.out` – KamilCuk Dec 27 '21 at 20:53
  • @KamilCuk I want to use the comand line for this. – niyojet344 Dec 27 '21 at 20:54
  • Does https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern answer your question? First read the file into a string - then escape. Because fo newlines the link follows to https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed . – KamilCuk Dec 27 '21 at 20:54
  • @niyojet344 if you solved the problem stated in your question then update your question to remove that and state what your new question is. – Ed Morton Dec 27 '21 at 20:55
  • @EdMorton i solved part of the problem and I updated it. I did not remove the part about the problem I already fixed so that someone else in the same situation can find it. Right now I need to figure out why the s command i "unterminated". – niyojet344 Dec 27 '21 at 20:59

1 Answers1

0

By using Is it possible to escape regex metacharacters reliably with sed the part with multiline replacement string, try the following:

IFS= read -d '' -r < <(sed -e ':a' -e '$!{N;ba' -e '}' -e 's/[&/\]/\\&/g; s/\n/\\&/g' other.html)
replaceEscaped=${REPLY%$'\n'}

sed -e "s_<p>The pen was blue.</p>_$replaceEscaped_" main/index.html
KamilCuk
  • 120,984
  • 8
  • 59
  • 111