2017-04-21 47 views
1

我試圖從一個shell腳本中的pom.xml文件中修改多個版本號,我不確定組件的版本號是什麼。我可以解析到版本,但是,不能替換該版本內聯。使用awk/sed來解析/替換XML內聯

pom.xml中看起來是這樣的:

... 
     <dependency> 
      <groupId>abc.efg</groupId> 
      <artifactId>service1</artifactId> 
      <version>0.0.10</version> 
     </dependency> 
     <dependency> 
      <groupId>abc.efg</groupId> 
      <artifactId>service2</artifactId> 
      <version>0.1.5</version> 
     </dependency> 
     <dependency> 
      <groupId>abc.efg</groupId> 
      <artifactId>service3</artifactId> 
      <version>0.0.1</version> 
     </dependency> 
... 

我完全新的shell腳本所以請原諒我,如果這是一個有點草率,但到目前爲止,我可以拉的服務版本的grep串起像;

$ grep -A 1 "service1" pom.xml | grep -Eo '[.0-9]*' 
$ 0.0.10 

但使用awk來代替內聯被證明是具有挑戰性的

$ grep -A 1 "service" pom.xml | grep -Eo '[.0-9]*' | sed 's/[,0-9]/3.2.1/g' 
$ 3.2.1.3.2.1.3.2.1 

輸出我正在尋找的是:

0.0.10 - > 3.2.1

$ grep -A 1 "service" pom.xml | grep -Eo '[.0-9]*' | #sedsyntax 
$ 3.2.1 

任何意見或指針,將不勝感激在這一點

+1

使用XML/HTML解析器(xmllint,xmlstarlet ...)。 – Cyrus

回答

1

您可以一次完成sed。 搜索模式,轉到下一行,替換版本號。

$ sed -r '/service1/!b;n;s/([0-9][.]?)+/1.1.11/' file 
<xml> 
    <dependency> 
    <groupId>abc.efg</groupId> 
    <artifactId>service1</artifactId> 
    <version>1.1.11</version> 
    </dependency> 
    <dependency> 
    <groupId>abc.efg</groupId> 
    <artifactId>service2</artifactId> 
    <version>0.1.5</version> 
    </dependency> 
    <dependency> 
    <groupId>abc.efg</groupId> 
    <artifactId>service3</artifactId> 
    <version>0.0.1</version> 
    </dependency> 
</xml> 

說明:

sed -r '/service1/!b;n;s/([0-9][.]?)+/1.1.11/' file 
     |________||___||_____________________|  
      |  |    | 
Pattern-----|  |    | 
Go next line--------|    | 
Replace Operation-------------------| 
-r switch (or -E) = Extended Regexp Support 
+0

喬治這是現貨,非常感謝你的詳細解釋和抽出時間幫助。 –

+0

針對'service12'更好地匹配'> service1 <''(在示例pom中未顯示)。 –

0

您的sed表達式中的直接問題是無法一次捕獲所有字符。

$ echo "0.0.10" | sed 's/[.0-9]*/3.2.1/g' 
3.2.1 

我強烈建議執行此操作時與像xmlstarlet的XML工具。