假設我有一個這樣的 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>
我想向-suffix所有 id附加一個唯一的后綴(比如,),這將包括 attributesid="..."和 selectors #...,并產生這樣的檔案:
<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 工具(例如sed, grep,awk以涵蓋盡可能多的情況的方式)來實作這一點?
我的嘗試:
我想出了以下sed命令:
sed -e 's/id="\([-_a-zA-Z0-9]*\)"/id="\1-suffix"/g;s/#\([-_a-zA-Z0-9]*\)/#\1-suffix/g' index.html
這實際上是兩個命令合二為一:
s/id="\([-_a-zA-Z0-9]*\)"/id="\1-suffix"/g- 替換 id 屬性id="..."s/#\(\[-_a-zA-Z0-9]*\)/#\1-suffix/g- 替換 id 選擇器#...
然而,它遠非完美。首先,它只支持雙引號中的雙屬性值,id="..."并且 id 值受限于它們必須匹配[-_a-zA-Z0-9]*. 其次,這與十六進制顏色沖突,因此白色 like#ffffff將獲得后綴#ffffff-suffix;#...如果id="..."存在適當的屬性,則像 id 選擇器一樣應該只獲得后綴。
實作這一目標的最佳方法是什么?
uj5u.com熱心網友回復:
您的檔案中有很多情況,正如您提到的顏色問題我的方法是使用
cat inputfile.html | while read a; do
some code
echo "$a" >> outputfile.html
done
話雖如此,您可以使用
b=$(expr "$a" : "regex")
要精確過濾您要修改的內容,然后才使用一些
sed
在 $b 上得到你想要的東西并將 $b 推入 $a
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367427.html
上一篇:兩個CSV檔案的比較
