【问题标题】:How to replace external CSS file link in html with the content of the CSS file using shell script?如何使用 shell 脚本将 html 中的外部 CSS 文件链接替换为 CSS 文件的内容?
【发布时间】:2019-12-20 08:45:53
【问题描述】:

我有一个 HTML 文件,其中包含指向外部 CSS 和 JS 文件的链接。我需要用 CSS 和 JS 文件的内容替换外部链接。我的 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">

现在我想用 css/styles.css 文件的内容替换 &lt;link href="css/styles.css" rel="stylesheet"/&gt;

我尝试使用 sed。我首先创建了两个变量

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

然后

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

但我收到如下错误:

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

如何解决这个问题。任何获得预期结果的替代方法也是受欢迎的。

【问题讨论】:

标签: javascript html css awk sed


【解决方案1】:

错误来自变量中的“/”字符。 您可以在通过 sed 之前转义“/”。

例如:

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

你应该对两者都这样做,以防你的 css 文件中也有“/”。

【讨论】:

    猜你喜欢
    • 2020-08-03
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多