In Linux, how does one read and write XML using shell scripts? An existing config. xml
<? XML version = "1.0" encoding = "UTF-8" ?>
< Config >
< Server-IP > 192.168.1.45 </ Server-IP >
< Server-Port > 1209 </ Server-Port >
< Repository-temp-Path > /Home/John </ Repository-temp-Path >
</ Config >
You need to modify the "server-IP", "server-port" and "import-path", and write the data using the shell script parameters $1, $2, $3.
Idea 1: Use SED
The first thought is to use sed regular match to replace the implementation and write a shell script, which is like this:
# ! /Bin/sh
If [$ # -Ne 3]; then
Echo " Usage: argument 1: ip_address 2: server_port 3: temp_path "
Exit 1
Fi
IP = $1
Port = $2
Dirt = $3
Echo"Change values in config. xml..."
Sed"S/<server-ip>. * <\/Server-ip>/<server-IP >$ {IP} <\/Server-ip>/; S/<server-port>. * <\/Server-port>/<server-port >$ {port} <\/Server-port>/; S/<repository-temp-path>. * <\/repository-temp-path>/<repository-temp-path >$ {dirt} <\/repository-temp-path>/"Config. xml> config. xml
Echo"Done."
Test and call$./ABC. Sh 192.168.1.6 9909 \/home \/ABC"Yes, but the environment variable is not, for example:$./ABC. Sh 192.168.1.6 9909 $ home \/ABC", Because the environment variable is parsed first, there is a conflict between the backslash Escape Character and sed replacement.
Implement with another idea
Another idea is to directly output the XML content and test it.Very usefulIt is easy to use, and there is no problem of escape characters with backslash and environment variables:
# ! /Bin/sh
If [$ # -Ne 3]; then
Echo " Usage: argument 1: ip_address 2: server_port 3: temp_path "
Exit 1
Fi
IP = $1
Port = $2
Dirt = $3
Echo"Change values in config. xml..."
Cat <EOF> config. xml
<? XML version ="1.0"Encoding ="UTF-8"?>
<Config>
<Server-ip>$ {IP}</Server-ip>
<Server-port>$ {Port}</Server-port>
<Repository-temp-path>$ {Dirt}</Repository-temp-path>
</Config>
EOF
Echo"Done."Idea 3: Use xmlstarlet
XML + shell = xmlstarlet
$ Xmlstarlet ed-U/config/Server-IP-V 192.168.1.6-U/config/Server-Port-V 9909-U/config/repository-temp-path-V/home/ bbb input. XML
<? XML version = " 1.0 " Encoding = " UTF-8 " ?>
<Config>
<Server-ip> 192.168.1.6 </Server-ip>
<Server-port> 9909 </Server-port>
<Repository-temp-path>/home/BBB </repository-temp-path>
</Config> idea 4: Use javastproc
In many Linux systems, for example, centos has installed javastproc by default. Therefore, you can use XSLT to easily convert one XML to another. For specific usage, see this webpage.