如何使用标准 unix 命令将后缀附加到 HTML 文件中的 ID?

How do I append a suffix to ids in a HTML file using standard unix commands?

假设我有一个这样的 HTML 文件:

<body>
    <div id="a">
       content of div a
       <div id="b"> content of div b </div>
       <div id="c"> content of div c </div>
    </div>
    <style>
      #a {color: red; }
      #b {color: green; }
      #c {color: blue; }
    </style>
</body>

我想为所有 ID 添加一个唯一的后缀(比如 -suffix),这将包括属性 id="..." 和选择器 #...,并生成如下文件:

<body>
    <div id="a-suffix">
       content of div a
       <div id="b-suffix"> content of div b </div>
       <div id="c-suffix"> content of div c </div>
    </div>
    <style>
      #a-suffix {color: red; }
      #b-suffix {color: green; }
      #c-suffix {color: blue; }
    </style>
</body>

我如何使用标准 unix shell 工具(例如 sedgrepawk 以涵盖尽可能多的情况的方式完成此操作?

我的尝试:

我想到了以下 sed 命令:

sed -e 's/id="\([-_a-zA-Z0-9]*\)"/id="-suffix"/g;s/#\([-_a-zA-Z0-9]*\)/#-suffix/g' index.html

这实际上是两个命令合二为一:

然而,它远非完美。首先,它只支持双引号 id="..." 中的双属性值,并且 id 值受到限制,因为它们必须匹配 [-_a-zA-Z0-9]*。其次,这与十六进制颜色冲突,所以像 #ffffff 这样的白色会得到一个后缀 #ffffff-suffix;如果存在适当的属性 id="...",像 #... 这样的 id 选择器应该只得到一个后缀。

完成此任务的最佳方法是什么?

你的文件中有很多案例,正如你提到的颜色问题 我的方法是使用

逐行处理文件
cat inputfile.html | while read a; do
some code
echo "$a" >> outputfile.html
done

话虽如此,您可以使用

b=$(expr "$a" : "regex")

要精确过滤您要修改的内容,然后再使用一些

sed

在 $b 上得到你想要的并将 $b 推入 $a