【发布时间】:2018-12-25 22:44:17
【问题描述】:
我有一个类似如下的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<csw:GetRecordByIdResponse xmlns:csw="http://www.opengis.net/cat/csw/2.0.2">
<xmlns:gmi="http://sdi.eurac.edu/metadata/iso19139-2/schema/gmi" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gml="http://www.opengis.net/gml" xmlns:geonet="http://www.fao.org/geonetwork" gco:isoType="gmd:MD_Metadata">
<gmd:onLine>
<gmd:CI_OnlineResource>
<gmd:linkage>
<gmd:URL>http://server.test.it/geoserver/test_product/wms?SERVICE=WMS&TIME=2018-06-14T10:59:00Z&</gmd:URL>
</gmd:linkage>
<gmd:protocol>
<gco:CharacterString>OGC:WMS-1.1.1-http-get-map</gco:CharacterString>
</gmd:protocol>
<gmd:name>
<gco:CharacterString>test_product:test_product</gco:CharacterString>
</gmd:name>
<gmd:description>
<gco:CharacterString>test_product:test_product</gco:CharacterString>
</gmd:description>
</gmd:CI_OnlineResource>
</gmd:onLine>
</csw>
我想将 标记的内容替换为以下内容:
我曾经在bash中使用sed命令:
correct_url='http://server.test.it/geoserver/test_product/wms?SERVICE=WMS&version=1.1.0&request=GetMap&layers=test_product:test_product&styles=&bbox=140442.2309,3739661.3694,1330442.2309,2564661.3694&width=768&height=576&srs=EPSG:32632&format=application/openlayers&TIME=2018-06-14T10:59:00Z&'
sed -i 's/<gmd:URL>\(.*\)<\/gmd:URL>/<gmd:URL>'"${correct_url}"'<\/gmd:URL>/' xml_file.xml
它给了我一个错误:
sed: -e expression #1, char 52: `s' 的未知选项
你能告诉我我做错了什么吗?
更新:
使用@rubystallion 的建议,我尝试转义所有特殊字符:
correct_url='http://server.test.it/geoserver/test_product/wms?SERVICE=WMS&version=1.1.0&request=GetMap&layers=test_product:test_product&styles=&bbox=140442.2309,3739661.3694,1330442.2309,2564661.3694&width=768&height=576&srs=EPSG:32632&format=application/openlayers&TIME=2018-06-14T10:59:00Z&'
correct_url_escaped="${correct_url//\//\\\/}"
correct_url_escaped="${correct_url_escaped//&/\\&}"
correct_url_escaped="${correct_url_escaped/\?/\?}"
correct_url_escaped="${correct_url_escaped/\?/\?}"
correct_url_escaped="${correct_url_escaped//\;/\;}"
correct_url_escaped="${correct_url_escaped//\=/\=}"
sed -i 's/<gmd:URL>\(.*\)<\/gmd:URL>/<gmd:URL>'"${correct_url_escaped}"'<\/gmd:URL>/' xml_file.xml
但我仍然收到错误:
sed: -e expression #1, char 47: `s' 的未知选项
我还是错过了什么吗?
【问题讨论】:
-
不要使用
sed修改XML;相反,请使用可识别 XML 的工具。 -
您的 XML 无效:
xmllint返回许多namespace error : Namespace prefix gmd on ... is not defined。 -
@choroba 我添加了命名空间。我忘记写了
-
Don't Parse XML/HTML With Regex. 我建议使用 XML/HTML 解析器 (xmlstarlet, xmllint ...)。
-
@Cyrus 类似于 xmlstarlet ed -u "//gmd:url" -v $correct_url xml_file.xml ?