2016-10-10 85 views
-1

我有一個POM.xml文件,它具有像「artifactId」&「版本」的詳細信息,目前我正試圖通過Shell腳本從pom.xml中獲取這些詳細信息。通過shell腳本從pom.xml文件獲取根詳細信息

注意:我不想從依賴性塊打印「版本」和「artifactID」。

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd"> 

<modelVersion>4.0.0</modelVersion> 

<groupId>com.javatpoint.application1</groupId> 
<artifactId>my-application1</artifactId> 
<version>1.0</version> 
<packaging>jar</packaging> 

<name>Maven Quick Start Archetype</name> 
<url>http://maven.apache.org</url> 

<dependencies> 
    <dependency> 
    <groupId>junit</groupId> 
    <artifactId>junit</artifactId> 
    <version>4.8.2</version> 
    <scope>test</scope> 
    </dependency> 
</dependencies> 

</project> 

我通過grep的,但沒有運氣:(嘗試。

回答

1

我會推薦安裝xpath,它可以通過012安裝。由於xpath是一個xml解析器,因此您可以更自信地獲得正確的xml和基於正則表達式的解決方案。

這裏是你的文件的一個示例:

#!/bin/bash 

function get_xpath_value { 
    xml=$1 
    path=$2 
    if [ -f $xml ]; then 
     # xpath returns <foo>value</foo>, so we need to unpack it 
     value=$(xpath $xml $path 2>/dev/null | perl -pe 's/^.+?\>//; s/\<.+?$//;') 
     echo -n $value 
    else 
     echo 'Invalid xml file "$xml"!' 
     exit 1; 
    fi 
} 

pom_xml='foo.xml' 

artifactId=$(get_xpath_value $pom_xml 'project/artifactId') 
version=$( get_xpath_value $pom_xml 'project/version' ) 

echo "ArtifactId is $artifactId" 
echo "Version is $version" 

輸出

ArtifactId is my-application1 
Version is 1.0 
0

你想要什麼格式?

awk -F '>|<' '/version|artifactId/ {print $3}'file 
+0

感謝您的回覆@zxy。但其示出 MY-應用1 1.0 的junit 4.8.2 其打印的junit&從依賴4.8.2也阻塞。 – rKSH

0

這可以幫助?如果你有更多dependices阻止,那麼我們就必須重新設置標誌值

bash-3.2$ awk '/depend/{flag=1}flag&&/artifactId|version/{next}1' test.txt 
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd"> 

<modelVersion>4.0.0</modelVersion> 

<groupId>com.javatpoint.application1</groupId> 
<artifactId>my-application1</artifactId> 
<version>1.0</version> 
<packaging>jar</packaging> 

<name>Maven Quick Start Archetype</name> 
<url>http://maven.apache.org</url> 

<dependencies> 
    <dependency> 
    <groupId>junit</groupId> 
    <scope>test</scope> 
    </dependency> 
</dependencies> 
0
awk -F '<[^>]*>' '/<dependencies>/,/<\/dependencies>/{next} /artifactId/{$1=$1;print "Artifact IF is:" $0} /version/ {$1=$1;print "Version is:" $0}' input.xml 
Artifact IF is: my-application1 
Version is: 1.0 

上述代碼中,第一忽略dependencies塊之間的文本。之後,它搜索artifactid並打印其值。版本類似。字段分隔符被定義爲照顧xml標籤。

相關問題