简体   繁体   English

如何使用shell脚本将html中的外部CSS文件链接替换为CSS文件的内容?

[英]How to replace external CSS file link in html with the content of the CSS file using shell script?

I have an HTML file with links to external CSS and JS files.我有一个 HTML 文件,其中包含指向外部 CSS 和 JS 文件的链接。 I need to replace the external links with the content of the CSS and JS files.我需要用 CSS 和 JS 文件的内容替换外部链接。 My HTML file looks like :我的 HTML 文件看起来像:

<?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现在我想用 css/styles.css 文件的内容替换<link href="css/styles.css" rel="stylesheet"/>

I tried using sed.我尝试使用 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.任何获得预期结果的替代方法也是受欢迎的。

The error is from the '/' characters present in your variable.错误来自变量中存在的“/”字符。 You can escape the '/' before putting it through sed.您可以在通过 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.您应该对两者都执行此操作,以防万一您的 css 文件中也有“/”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM