[英]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.