Bash从xml解析数据

时间:2014-02-18 16:17:12

标签: xml bash parsing

我不是很擅长这样做,所以我需要亲自动手。

我有以下输出,我想解析来自的数据:

实际输出:

<connection-pool name="name1" max-connections="50" min-connections="5">
<connection-factory factory-class="oracle.jdbc.pool.OracleDataSource" user="user1" password="xxxx" url="jdbc:oracle:thin:@server1.domain.com:1550:name1" commit-record-table-name="">
<connection-pool name="name2" max-connections="50" min-connections="5">
<connection-factory factory-class="oracle.jdbc.pool.OracleDataSource" user="user2" password="xxxx" url="jdbc:oracle:thin:@server2.domain.com:1524:name2" commit-record-table-name="">
<connection-pool name="name3" max-connections="15" min-connections="5">
<connection-factory factory-class="oracle.jdbc.pool.OracleDataSource" user="user3" password="xxxx" url="jdbc:oracle:thin:@server3.domain.com:1528:name3" commit-record-table-name="">
<connection-pool name="name4" initial-limit="1" max-connections="10" min-connections="1" num-cached-statements="5">
<connection-factory factory-class="oracle.jdbc.pool.OracleDataSource" user="user4" password="xxxx" url="jdbc:oracle:thin:@server4.domain.com:1538:name4" commit-record-table-name=""/>
<connection-pool name="name5" initial-limit="1" max-connections="10" min-connections="1" num-cached-statements="5">
<connection-factory factory-class="oracle.jdbc.pool.OracleDataSource" user="user5" password="xxxx" url="jdbc:oracle:thin:@//server5.domain.com:1537/name5"/>

期望的输出:

name="name1" max-connections="50" min-connections="5" url="jdbc:oracle:thin:@server1.domain.com:1550:name1"
name="name2" max-connections="50" min-connections="5" url="jdbc:oracle:thin:@server2.domain.com:1524:name2"
name="name3" max-connections="15" min-connections="5" url="jdbc:oracle:thin:@server3.domain.com:1528:name3"
name="name4" max-connections="10" min-connections="1" url="jdbc:oracle:thin:@server4.domain.com:1538:name4"
name="name5" max-connections="10" min-connections="1" url="jdbc:oracle:thin:@//server5.domain.com:1537/name5"

如果有人可以帮助我,我将不胜感激,顺便说一句,它应该在bash中完成,因为我无法在所有生产服务器上安装软件。

提前感谢!!

1 个答案:

答案 0 :(得分:1)

由于这不是有效的XML,不妨使用sed:

sed -n '
  /<connection-pool /   {s///; s/\/\?>$//; s/ \(initial-limit\|num-cached-statements\)="[^"]*"//g; p} 
  /<connection-factory/ {s///; s/\/\?>$//; s/ \(factory-class\|user\|password\|commit-record-table-name\)="[^"]*"//g; p}
' connections.log | paste -d "" - -
name="name1" max-connections="50" min-connections="5" url="jdbc:oracle:thin:@server1.domain.com:1550:name1"
name="name2" max-connections="50" min-connections="5" url="jdbc:oracle:thin:@server2.domain.com:1524:name2"
name="name3" max-connections="15" min-connections="5" url="jdbc:oracle:thin:@server3.domain.com:1528:name3"
name="name4" max-connections="10" min-connections="1" url="jdbc:oracle:thin:@server4.domain.com:1538:name4"
name="name5" max-connections="10" min-connections="1" url="jdbc:oracle:thin:@//server5.domain.com:1537/name5"