2012-02-13 27 views
0

說我有下面的XML提取標籤:在shell腳本的另一個標籤相同級別的

<app-deployment> 
    <name>gr1</name> 
    <target>AdminServer</target> 
    <module-type>ear</module-type> 
    <source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path> 
    <security-dd-model>DDOnly</security-dd-model> 
    <staging-mode>stage</staging-mode> 
</app-deployment> 
<app-deployment> 
    <name>gr2</name> 
    <target>AdminServer</target> 
    <module-type>ear</module-type> 
    <source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path> 
    <security-dd-model>DDOnly</security-dd-model> 
    <staging-mode>nostage</staging-mode> 
</app-deployment> 
<app-deployment> 
    <name>gr3</name> 
    <target>AdminServer</target> 
    <module-type>ear</module-type> 
    <source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path> 
    <security-dd-model>DDOnly</security-dd-model> 
</app-deployment> 

我怎樣才能提取分期模式變量的值,說名爲應用程序部署GR2?

+0

沒有perl的解決方案請,因爲我是侷限於只用shell腳本解決方案,如用sed,awk中,等 – Codrguy 2012-02-13 23:24:27

+0

和您的XML將始終作爲完全格式化如上你的樣品? – shellter 2012-02-13 23:56:30

+0

是的,它是由另一個腳本生成的xml,所以格式將永遠是相同的 – Codrguy 2012-02-14 00:08:28

回答

1

許多人(包括我自己)會告訴你,使用基於reg-ex的工具來分析xml是愚蠢的任務,並且你應該使用爲xml解析而設計的工具。 Xpath應該爲此工作,而xmlstarlet將是一個可以快速安裝和使用的軟件包。這就是說,假設你的數據總是能夠很好地形成,那麼製作一個awk腳本來搜索1個模式,設置一個標誌,查找另一個模式,設置一個標誌等是很容易的。當您找到最終目標時,清理該行以提取所需的數據。

set -- gr2 
{ cat - <<-EOS 
<app-deployment> 
    <name>gr2</name> 
    <target>AdminServer</target> 
    <module-type>ear</module-type> 
    <source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path> 
    <security-dd-model>DDOnly</security-dd-model> 
    <staging-mode>nostage</staging-mode> 
</app-deployment> 
EOS 
} | awk ' 
    /[<]app-deployment/{a=1} 
    a && /[<]name[>]'"$1"'/{n=1} 
    a && n && /[<]staging-mode[>]/{ 
     sub(/[<]staging-mode[>]/,"", $0) 
     sub(/[<]\/staging-mode[>]/,"",$0) 
     print $0 
     exit 
    } 
    #dbg { print "a=" a "\tn=" n } 
    ' 

輸出

 nostage 

set -- gr3{ cat ... } |是一個測試工具,你會包裝,這是一個shell腳本,即

cat printXMLarg.bash 
#!/bin/bash 
    targ=$1; shift 
    awk ' 
    /[<]app-deployment/{a=1} 
    a && /[<]name[>]'"${targ}"'/{n=1} 
    a && n && /[<]staging-mode[>]/{ 
     sub(/[<]staging-mode[>]/,"", $0) 
     sub(/[<]\/staging-mode[>]/,"",$0) 
     print $0 
     exit 
    } 
    #dbg { print "a=" a "\tn=" n } 
    ' "${@}" 

,並呼籲像

printXMLarg.bash gr3 *.xml 

第二部分未經測試。讓我知道你是否有問題。

我希望這有助於

+0

非常感謝。這很好。我想使用sed或awk的原因是,我不知道在這個腳本將要使用的Linux機器上將有什麼類型的軟件包可用。所以我想,既然awk和sed總是會在那裏,這是我的情況。再次感謝您的回答。 – Codrguy 2012-02-14 01:01:30

+0

有沒有辦法改變上面的腳本,因爲它沒有staging-mode標籤,所以在傳遞grc3時(在我的問題中是例子xml的情況下)什麼都不返回?目前它由於某種原因返回nostage。 – Codrguy 2012-02-14 01:28:41

+0

固定,我想。否則,請告知我。晚安。 – shellter 2012-02-14 03:50:44

相關問題