通过shell脚本从pom.xml文件获取root详细信息

时间:2016-10-10 05:44:10

标签: xml bash shell unix scripting

我有一个POM.xml文件,其中包含" artifactId"等详细信息。 &安培; "版本"目前我正试图通过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但没有运气:(。

4 个答案:

答案 0 :(得分:1)

我建议安装xpath,可以通过yum install perl-XML-XPath进行安装。由于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

答案 1 :(得分:0)

你想要什么格式?

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

答案 2 :(得分:0)

这有帮助吗?如果你有更多的依赖块,那么我们必须重置标志值

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>

答案 3 :(得分: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标记。