【发布时间】:2021-09-02 20:15:36
【问题描述】:
我有一个包含多次用户名和密码的 xml 文件,以及需要动态更改的连接 URL。
<datasources>
<datasource jndi-name="java:jboss/datasources/TestFlow" pool-name="TestFlow" enabled="true" use-java-context="true" statistics-enabled="${wildfly.datasources.statistics-enabled:$ {wildfly.statistics-enabled:false}}">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<driver>h2</driver>
<security>
<user-name>test</user-name>
<password>test</password>
</security>
</datasource>
<datasource jta="false" jndi-name="java:/AdminDSource" poolname="AdminDSource" enabled="true" use-java-context="true">
<connection-url>jdbc:oracle:thin:@xxxxxx.xxxxxxx.xxxxxxxx-1.rds.amazonaws.com:xxxx:ORCL</connection-url>
<driver>oracle</driver>
<security>
<user-name>aldo</user-name>
<password>aldo</password>
</security>
</datasource>
</datasources>
在上面我想将第一次出现的连接 URL、用户名和密码更改为一些所需的值
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<user-name>test</user-name>
<password>test</password>
改成
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-2;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<user-name>Atom</user-name>
<password>Atom</password>
同样的,第二次出现相同的地方要改变
<connection-url>jdbc:oracle:thin:@{Content after the @ to be changed}</connection-url>
<user-name>{aldo to username}</user-name>
<password>{aldo to password}</password>
我已尝试以下方法来更新用户名和密码,
for filename in *.xml; do
if grep -q '<driver>h2</driver>' "$filename"; then
sed -i.bak 's/<user-name>test<\/user-name>/<user-name>Atom<\/user-name>/g' "$filename"
fi
if grep -q '<driver>h2</driver>' "$filename"; then
sed -i.bak 's/<password>test<\/password>/<password>Atom<\/password>/g' "$filename"
fi
if grep -q '<driver>oracle</driver>' "$filename"; then
sed -i.bak 's/<user-name>aldo<\/user-name>/<user-name>username<\/user-name>/g' "$filename"
fi
if grep -q '<driver>oracle</driver>' "$filename"; then
sed -i.bak 's/<password>aldo<\/password>/<password>password<\/password>/g' "$filename"
fi
done
但我希望有一个脚本来进行所有理想的更改。
【问题讨论】:
-
您发布的是单个脚本,虽然效率不高。顺便说一句,是否保证在您的 XML 中,开始和结束标记将始终位于同一物理行中?
-
最快的方法——除非你有 100 多个 xml 文件——是打开你最喜欢的文本编辑器并进行搜索/替换...比编写和调试复杂的脚本要快得多。
-
查看 xmlstarlet 或 xsltproc
标签: xml bash shell sed xmlstarlet