如何使用 unix 命令將 xml 檔案中的一行替換為儲存在變數或檔案中的一組行?

如何使用 unix 命令將 xml 檔案中的一行替換為儲存在變數或檔案中的一組行?

我有一個 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

相關內容