gpt4 book ai didi

linux - 使用具有 xml 值的变量的 awk 模式匹配

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:36 25 4
gpt4 key购买 nike

这是我的 awk 脚本。它在一个名为 mAwk.awk 的文件中

#!usr/bin/awk -f
BEGIN {
FS="."
artifactPattern="/<artifactId>artifactName1|artifactName2<\\/artifactId>/"
# print "-------------" artifactPattern
}
{
toPrint = 1
if ($0 ~ /<dependencies>/) {
matches=1000;
}
else if ($0 ~ /<dependency>/) {
matches +=100;
}
else if ($0 ~ /<\/dependency>/) {
matches =1000;
}
else if ($0 ~ /<groupId>(com.group1.*)|(com.group2.*)|(com.group3.*)<\/groupId>/) {
matches += 10;
}
# else if($0 ~ /<artifactId>artifactName1|artifactName2<\/artifactId>/){
else if($0~artifactPattern){
matches += 1;
}
else if ($0 ~ /<version>[0-9]+\.[0-9]+\.[0-9]+<\/version>/) {
print "debugging: matched 1 -", matches
if (matches == 1111) {
lastPart="0-SNAPSHOT</version>"
print $1 "." $2+1 "." lastPart;
matches -= 11;
toPrint = 0
}
}
else if ($0 ~ /<\/dependencies>/) {
matches=0
}
if ( toPrint == 1) {
print $0
}
}
END {
}

现在这是 xml 文件的结构(它是一个 pom.xml),以防万一:

<project>
<random tags/>

<dependencies>
<dependency>
<groupId>data</groupId>
<artifactId>data</artifactId>
<version>1.2.3</version>
</dependency>
... repeat...
</dependencies>
</project

问题是,如果我使用这条线:

# else if($0 ~ /<artifactId>payment-common|test2-common<\/artifactId>/){

它匹配得很好,而不是它下面的那个,但是当我把值放在一个变量中时,它失败了。这是怎么回事?

我的最终目标是通过 shell 脚本调用它,例如...

awk -v pattern=`cat ./artifactPatterns.txt` mAwk.awk -f myFile.xml

并且 artifactPatterns.txt 看起来就像变量保存在 awk 文件中一样,示例:

/<artifactId>artifactName1|artifactName2<\\/artifactId>/

我已经尝试了很多东西,但似乎没有任何效果,谢谢您的宝贵时间!

最佳答案

去掉 artifactPattern 值周围的 // 分隔符。这些是正则表达式文字的语法,它们不属于字符串。 ~ 运算符的使用意味着它是一个正则表达式。

而且由于 / 不是定界符,因此您无需在值内对它进行转义。

artifactPattern="<artifactId>artifactName1|artifactName2</artifactId>"

此外,$0 ~/pattern/ 可以简化为 /pattern/ —— 当正则表达式文字本身出现时,它默认匹配整行.

关于linux - 使用具有 xml 值的变量的 awk 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com