2

I have an HTML file with links to external CSS and JS files. I need to replace the external links with the content of the CSS and JS files. My HTML file looks like :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta http-equiv="Expires" content="-1"/>
        <meta http-equiv="Pragma" content="no-cache"/>
        <link href="css/styles.css" rel="stylesheet"/>
        <script type="text/javascript" src="js/d3.v2.min.js"></script>
        <script type="text/javascript" src="js/sorttable.js"></script>
        <script type="text/javascript">

Now I want to replace the line <link href="css/styles.css" rel="stylesheet"/> with the contents of css/styles.css file

I tried using sed. I first created two variables

export OLD_STRING="<link href=\"css/styles.css\" rel=\"stylesheet\"/>" 
export NEW_STRING="<style>\n""$(cat css/styles.css)""\n<style>"

then

sed -i "s/'$OLD_STRING'/'$NEW_STRING'/g" index.html 

But I am getting errors like :

sed: -e expression #1, char 49: unknown option to `s'

How to solve this problem. Any alternative way to get the desired outcome is also welcome.

saurav
  • 359
  • 1
  • 6
  • 18
  • [Don't Parse XML/HTML With Regex.](https://stackoverflow.com/a/1732454/3776858) I suggest to use an XML/HTML parser (xmlstarlet, xmllint ...). – Cyrus Aug 13 '19 at 18:56

1 Answers1

2

The error is from the '/' characters present in your variable. You can escape the '/' before putting it through sed.

For example:

old_string=`echo "$old_string" | sed "s/\//\\\//g"`
new_string=`echo "$new_string" | sed "s/\//\\\//g"`

You should do this to both, just in case you have '/' in your css file too.

momo
  • 21
  • 2