【问题标题】:Why does awk "not in" array work just like awk "in" array?为什么 awk "not in" 数组的工作方式与 awk "in" 数组一样?
【发布时间】:2012-06-11 00:50:49
【问题描述】:

这是一个 awk 脚本,它尝试根据第一列设置两个文件的差异:

BEGIN{
    OFS=FS="\t"
    file = ARGV[1]
    while (getline < file)
        Contained[$1] = $1
    delete ARGV[1]
    }
$1 not in Contained{
    print $0
}

这是TestFileA:

cat
dog
frog

这里是TestFileB:

ee
cat
dog
frog

但是,当我运行以下命令时:

gawk -f Diff.awk TestFileA TestFileB

我得到的输出就像脚本包含“in”一样:

cat
dog
frog

虽然我不确定“not in”对于我的意图是否是正确的语法,但我很好奇为什么它的行为与我写“in”时的行为完全相同。

【问题讨论】:

  • 我也找不到任何关于“不在”的文档,所以我同意这不是我最初意图的正确语法,尽管这不是实际问题。

标签: awk gawk


【解决方案1】:

我找不到任何关于element not in arraydoc

试试!(element in array)


我猜:awknot 视为未初始化的变量,因此 not 被评估为空字符串。

$1 not == $1 "" == $1

【讨论】:

  • 我无法从您的代码中看出您正在尝试做什么,即使我取出任性的“非”裸字,我仍然会遇到语法错误。试试 'awk --lint -f yourfile.awk yourdatafile
  • @starbolin:我认为您的意思是让您的评论附加到这个问题上,因为在这里附加它没有任何意义。您不应该遇到任何语法错误,因为脚本没有任何(其他)错误。
【解决方案2】:

我想出了这个。 ( x in array ) 返回一个值,所以要“不在数组中”,你必须这样做:

if ( x in array == 0 )
   print "x is not in the array"

或者在你的例子中:

($1 in Contained == 0){
   print $0
}

【讨论】:

    【解决方案3】:

    在我解决这个问题的方法中,我使用了以下if-else 语句:

    if($1 in contained);else{print "Here goes your code for \"not in\""}
    

    【讨论】:

      【解决方案4】:

      不确定这是否像你想要做的那样。

      #! /bin/awk # 将读入第二个 arg 文件并对令牌进行哈希处理 # 在第一列中找到。然后它将读取第一个 arg 文件并打印任何 # 第一列中带有标记的行与已定义的标记不匹配 开始{ OFS=FS="\t" 文件 = ARGV[1] while (getline &lt 文件) 包含[$1] = $1 # delete ARGV[1] # 不知道你在想什么 # for(i in Contained) {print Contained[i]} # 调试,不仅仅是虐待狂 关闭(ARGV[1]) } { if ($1 in Contained){} else { print $1 } }

      【讨论】:

        【解决方案5】:

        在 awk 命令行中我使用:

         ! ($1 in a)
        $1 pattern
        a array
        

        例子:

        awk 'NR==FNR{a[$1];next}! ($1 in a) {print $1}' file1 file2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-13
          • 2012-08-27
          • 1970-01-01
          • 1970-01-01
          • 2014-05-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多