【问题标题】:Compare file with variable list AWK将文件与变量列表 AWK 进行比较
【发布时间】:2011-01-06 14:17:08
【问题描述】:

我为自己试图完成一件看似简单的事情而磕磕绊绊。我有一个文件和一个换行符分隔的字符串列表。

文件:

Dat1 Loc1

Dat2 Loc1

Dat3 Loc1

Dat4 Loc2

Dat5 Loc2

我的清单是这样的:

日期1

日期2

日期3

日期4

我要做的是将列表与数据文件进行比较,并计算出现的唯一 Loc 的数量。我只对最大的计数感兴趣。在上面的示例中,当将列表与文件进行比较时,我基本上想要:

Dat1 匹配的 Loc1Count = 1

Dat2 匹配的 Loc1Count = 2

Dat3 匹配的 Loc1Count = 3

Dat4 匹配的 Loc2Count = 1

返回:Loc1 如果 Loc1Count/List 的长度 > 50%

现在,

我知道 awk 1 文件会逐行读取文件。此外,我知道 "echo "$LIST" | awk '/search for a line that contains this/" 将返回与该内部字符串匹配的行。尽管作为嵌套的 awks,但我无法成功地将这些想法结合起来,更不用说如何计算“loc1”与“loc2”(顺便说一下,这将是随机字符串,而不是形式标准)

我觉得这很简单,但我的头撞到了墙上。有任何想法吗?这足够清楚吗?

【问题讨论】:

  • 您正在寻找的功能(如 ghostdog74 的 答案所示)称为关联数组。

标签: file sed awk grep


【解决方案1】:
list="Dat1 Dat2 Dat3 Dat4"
awk -vli="$list" 'BEGIN{
   # here list from shell is converted to awk array "list". 
   m=split(li,list," ") 
}
{
    # go through the list 
    for(i=1;i<=m;i++){
        if($1 == list[i]){
            # if Dat? is found in list, print , at the same time
            print $1" matched Locount="$2" "++data[$2]   # increment the count for $2 and store in loc array
            loc[$2]++ 
        }
    }
} 
END{
    # here returns loc1 count
    loc1count=loc["Loc1"]
    if(( loc1count / m *100 ) > 50) {
        print "Loc1 count: "loc1count
    }
} ' file

输出

$ ./shell.sh
Dat1 matched Locount=Loc1 1
Dat2 matched Locount=Loc1 2
Dat3 matched Locount=Loc1 3
Dat4 matched Locount=Loc2 1
Loc1 count: 3

【讨论】:

  • 糟糕 - 我很难找到如何包含我的变量 "$LIST" awk: 非法字段 $(), name "LIST" source line number 1 return when: msplit($LIST,list ,"\n")
  • awk 变量和shell 变量是不同的。要将 shell 变量传递给 awk,请使用 -v 选项。
  • -v LIST="${LIST}" 在 awk 中传递变量看起来效果很好。但是,现在我对换行符有困难。错误 - 字符串 Dat1 中的换行符 ... 在源代码行 1
  • 展示如何获得 $LIST。或者更好的是,显示您拥有的代码。
  • 投票,awk、ghostdog 的伟大使用,你介意对代码做一些评论吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多