3

一段时间以来一直想知道这在 AWK 中是否可行,但过去一直在解决它。

下面我用一年中的 3 个月初始化一个数组……为了便于阅读,我省略了其他 9 个月。然后这些月份在 if 语句中用作正则表达式的一部分,但 AWK 不喜欢它。我似乎在 awk/gawk 手册中找不到任何关于这种语义的内容......我真的坚持重复 12 次相同的代码吗?是否可以在循环中使用 arr[i] 作为变量名的子字符串?我在下面编写了伪代码,以了解我要完成的工作。我知道它在 SNOBOL 中是可行的 ;-) 谢谢!

  BEGIN {   
        arr[0] = "AUG"
        arr[1] = "SEP"
        arr[2] = "OCT"
    }
    {
        for(i in arr)
        {
            if($1 ~ /arr[i]/)
            {
             #Controls flows into here if $1 matches AUG, SEP, OCT
             #Furthermore, pretend I want to intialize a variable like AUGseen:
                       arr[i]seen = 1
            }
        }
    }

如果这些事情中的任何一个是可行的,我将不胜感激!

4

3 回答 3

3

您可以match用于动态正则表达式。

if(match($1, arr[i]))
于 2010-08-24T17:29:50.907 回答
1

我不认为 awk 支持这个概念,但使用函数将同样有效:

# fail is the default return code, the user should insure that it does not
# exist as a key to arr
function amatch(candidate, arr, fail) {
  for (i in arr) 
      if ( match(candidate,array[i]) ) return i;
  return fail;
}
于 2010-08-24T17:42:58.607 回答
1

这是另一种选择,它不使用数组。(您可以将数组保留用于其他目的)

BEGIN {
  dates="AUG|SEP|OCT"

}
{
  if( $1 ~ dates) {
     print ...
  }

}
于 2010-08-25T00:25:23.947 回答