簡體   English   中英

使用帶有xml值的變量進行awk模式匹配

[英]awk pattern matching using variable with xml value

所以這是我的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值的定界符。 這些是regexp文字的語法,它們不屬於字符串。 使用~運算符表示它是一個正則表達式。

並且由於/不是定界符,因此您無需在值內將其轉義。

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

同樣, $0 ~ /pattern/可以簡化為/pattern/ -當一個regexp文字本身出現時,它默認與整行匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM