我有一个200页的网站,想实现链接的规范化。
我使用我的ftp客户端将网站下载到本地目录中,并希望在每个页面的<head>
标记下拥有规范元标记。
所以,对于第 1 页,我想转换
<head>
到
<head>
<link rel="canonical" href="http://www.site.com/page1.htm" />
并使用 sed 在整个本地目录 (page1.htm、page2.htm...第200.htm页)。 谢谢。
sed
,awk
不是为处理HTML而设计的。请参阅正则表达式匹配开放标签,但 XHTML 自包含标签除外
使用 xslt、bash、xmlstarlet 的演示
cd /where/HTML_pages/exists
for file in *html; do xmlstarlet transform --html <(cat<<EOF
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" >
<xsl:output method="html" encoding="utf-8"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="head">
<xsl:copy>
<xsl:apply-templates/>
<xsl:if test="not(link)">
<link rel="canonical" href="http://www.site.com/$file" />
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
EOF) >/"tmp/$file" "$file" && mv "/tmp/$file" "$file"
done
编辑
一个更好/更合适的纯XSLT解决方案仍然使用XMLSTARLET,但现在bash不再是强制性的:
文件xsl.xslt
:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" encoding="utf-8" />
<!-- where are not making a HTML from scratch,
so we will copy what's exists -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!-- looking for "head" tag -->
<xsl:template match="head">
<xsl:copy>
<xsl:apply-templates />
<!-- if "link" tag not exists ... -->
<xsl:if test="not(link)">
<!-- we add the new "link" tag... -->
<link>
<xsl:attribute name="rel">
<!-- with a fixed string attribute... -->
<xsl:text>canonical</xsl:text>
</xsl:attribute>
<xsl:attribute name="href">
<!-- and a dynamic string attribute ("link" parameter) -->
<xsl:value-of select="$link" />
</xsl:attribute>
</link>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
外壳代码 :
cd /where/HTML_pages/exists
for file in *html; do
xmlstarlet transform
--html
xsl.xslt
-s "link=http://www.site.com/$file" "$file" > "/tmp/$file" &&
mv "/tmp/$file" "$file"
done
这将添加您想要的元素,<head>
当前页面作为变量
我分两个阶段为自己解决了这个问题:
-
find ./ -name '*.html' | while read i; do echo $i; sed -i 's#</head>#<link rel="canonical" href="'$i'" />n</head>#I' ./$i;done
2. find ./ -name '*.html' | while read i; do echo $i; sudo sed -i 's#<link rel="canonical" href=".#<link rel="canonical" href="http://domainname.here#g' ./$i;done;