繁体   English   中英

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

[英]Getting root details from pom.xml file through shell script

我有一个 POM.xml 文件,其中包含诸如“artifactId”和“version”之类的详细信息,目前我正尝试通过 Shell 脚本从 pom.xml 中提取这些详细信息。

注意:我不想从依赖项块中打印“version”和“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 但没有运气:(。

我建议安装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

你想要什么格式?

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

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

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>
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标签。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM