-1

在 Stackoverflow 和 Google 上搜索过,最接近的答案是:

sed -i -e 's|<element id="lastupdate">\([0-9]\{0,\}\)</element>|<element id="lastupdate">'"$(date -d @${contents})"'</element>|g' /var/www/html/index.html

仅在标签内容为空时有效。如果已经更改,则不能再使用。

我们的想法是更改此标签 ID 内的任何内容,而不仅仅是在它为空时。

这是关于使用 awk 读取标签 id 内任何内容的一个很好的答案:https ://stackoverflow.com/a/13148004/5623661 。但它仅适用于读取(使用 awk)而不适用于附加/替换(使用 sed)。

另一个想法是不仅有一种方法来替换:而且另一种方法是附加到给定标签内的任何内容中。

是否可以使用适用于 HTML 的工具而不是专门为 XML 制作的工具?试过:

输入:xmlstarlet ed --update '//element[@id="daipeg"]' --value 'new' index.html

输出:

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Status - Floflis</title>
    <link rel="shortcut icon" href="icon.ico" type="image/x-icon"/>
    <link rel="icon" href="icon.ico" type="image/x-icon"/>
  </head>
  <body><h1>Floflis Status</h1><ul><li><p>Is DAI pegged to USD? <b><element id="daipeg">No</element></b></p></li><li><p>DAI now worth <b><element id="daiusd"/> USD</b></p></li></ul><p>Last updated in <element id="lastupdate"/> (updates every 5 minutes).</p><a href="https://floflis.github.io/" target="_blank">Main site</a> | <a href="https://floflis.github.io/blog" target="_blank">Blog</a> | <a href="https://floflis.github.io/docs" target="_blank">Documentation</a> | <a href="./api.html">DEV</a>
</body>
</html>

期望的结果:将里面的“No”更改<element id="daipeg">No</element>为“new”,直接进入 index.html 文件。

4

1 回答 1

1

(对应标签,我用的是1.6.1版本。)

如果您修复了命名空间问题并添加了一个--inplace选项(替换element值):

test "${bettersorrythansafe}" || cp file.xhtml file.xhtml.was
xmlstarlet ed --inplace -N X='http://www.w3.org/1999/xhtml' \
    --update '//X:element[@id="daipeg"]' --value 'new' file.xhtml

或者,使用简短选项和默认命名空间的快捷方式:

xmlstarlet ed -L -u '//_:element[@id="daipeg"]' -v 'new' file.xhtml

请注意,该--inplace选项在 xmlstarlet.txt中有所提及, 但在用户指南中并未提及。有关_命名空间快捷方式的更多信息,请参阅用户指南 ch。5 .

要附加到值,例如:

xmlstarlet ed -L -N X='http://www.w3.org/1999/xhtml' \
    --var peg '//X:element[@id="daipeg"]' \
    --var res "$((3 * 7 * 2))" \
    -u '$peg' -x 'concat($peg," and then ",$res)' file.xhtml
于 2021-12-02T11:51:31.300 回答