3

我想处理形式的字符串:

PREFIX_TYPE_N,DATA

那么,*awk (gawk, mawk, nawk) 是否支持在已匹配字符串的操作中包含模式匹配?像这样的东西(当然,对我不起作用):

*awk 'BEGIN { FS="," }
     /PREFIX/ {
                /TYPE_1/  {printf "[TYPE1] [DATA: $2]"}    // <-- included pattern 
                /TYPE_2/  {printf "[TYPE2] [DATA: $2]"}    // <-- another included pattern
                ...                                        // <-- some more included patterns
              }' "filename"

还是我还需要 if/else 或 switch/case?

4

2 回答 2

3

不完全那样,但非常接近,因为有一个正则表达式匹配运算符 (~):

BEGIN { FS="," }
/PREFIX/ {
            if ($1 ~ "TYPE_1") {printf "[TYPE1] [DATA: $2]"}    // <-- included pattern 
            if ($1 ~ "TYPE_2") {printf "[TYPE2] [DATA: $2]"}    // <-- another included pattern
            ...                                        // <-- some more included patterns
          }

请注意,因为第一个模式匹配已经进入它的块并且只处理了一行,所以在块中只有 ifs 很好。

如果你真的想要模式的易读性,你可以这样做:

BEGIN { FS="," }
/PREFIX/ { //stuff to do for all prefixes, before specific handling
          data = $2 }
/PREFIX_TYPE_1/ { type = "TYPE_1"; }
/PREFIX_TYPE_2/ { type = "TYPE_2"; }
/PREFIX/ { //stuff to do for all prefixes, after specific handling 
          printf("[%s] [DATA: $2]", type, data)
          }
于 2012-09-05T14:24:03.387 回答
1

你可以在 gawk 中这样做:

awk 'BEGIN { FS="," }
     /PREFIX/ {
                if (/TYPE_1/)  {printf "[TYPE1] [DATA: $2]"}    // <-- included pattern 
                if (/TYPE_2/)  {printf "[TYPE2] [DATA: $2]"}    // <-- another included pattern
                ...                                        // <-- some more included patterns
              }' "filename"

这里/TYPE_1/相当于$0 ~ /TYPE_1/. 在文档中查找详细信息(第 6.1.2 部分)。

于 2012-09-05T14:30:50.777 回答