![如何使用 unix 命令將 xml 檔案中的一行替換為儲存在變數或檔案中的一組行?](https://rvso.com/image/1414653/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20unix%20%E5%91%BD%E4%BB%A4%E5%B0%87%20xml%20%E6%AA%94%E6%A1%88%E4%B8%AD%E7%9A%84%E4%B8%80%E8%A1%8C%E6%9B%BF%E6%8F%9B%E7%82%BA%E5%84%B2%E5%AD%98%E5%9C%A8%E8%AE%8A%E6%95%B8%E6%88%96%E6%AA%94%E6%A1%88%E4%B8%AD%E7%9A%84%E4%B8%80%E7%B5%84%E8%A1%8C%EF%BC%9F.png)
我有一個 xml 文件
其中需要搜尋的行是:
SEARCH='<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC>'
此搜尋到的值需要替換為以下變數中的值,或者也可以儲存在另一個檔案中:
REPLACE='<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC><ErrorContext><CompatibilityMode>0</CompatibilityMode><ErrorOutput>1</ErrorOutput>.......some more tags.....</MethodContext>
'
如何使用 SED 或 AWK 等 unix 指令來完成此操作? (這裡SEARCH需要換成REPLACE。
答案1
是的,可以用 sed 完成,但我同意 Jens 的觀點。我建議使用適當的工具(例如 python + lxml 庫)來搜尋和取代標籤。
答案2
據我所知要轉義的字符:
awk '/<\?xml version="1.0" encoding="UTF-8" standalone="no"\?><SSC>/ {print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><SSC><ErrorContext><CompatibilityMode>0</CompatibilityMode><ErrorOutput>1</ErrorOutput>.......some more tags.....</MethodContext>"}' <<< '<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC>'
- 在搜尋欄位中:您想轉義?字符由 \?
- 在 REPLACE 欄位中:您想用 \ 轉義“字元”
或者,如果您需要使用變量,您也可以在 SEARCH 欄位中轉義 " 並將字元轉義兩次,一次儲存在變數中,兩次回顯!
SEARCH_escaped=`sed -e 's/\?/\\\?/g' -e 's/\"/\\\"/g' <<< $SEARCH`
REPLACE_escaped=`sed 's/\"/\\\"/g' <<< $REPLACE`
awk "/$SEARCH_escaped/ {print \"$REPLACE_escaped\"}" <<< $SEARCH