【问题标题】:how to count number of lines of a specific entry under a specific pattern using awk?如何使用awk计算特定模式下特定条目的行数?
【发布时间】:2018-06-05 00:13:34
【问题描述】:

我有一个文本文件,其模式如下所示

Sample1
Feature 1
A
B
C
Feature 2
A
G
H
L
Sample2
Feature 1
A
M
W
Feature 2
P
L

我正在尝试计算每个样本中每个功能的条目数。所以我想要的输出应该是这样的:

Sample1
Feature 1: 3
Feature 2: 4

Sample2
Feature 1: 3
Feature 2: 2

我尝试使用以下 awk 命令:

$ awk '{if(/^\Feature/){n=$0;}else{l[n]++}}
       END{for(n in l){print n" : "l[n]}}' inputfile.txt > result.txt

但它给了我以下输出

Feature 1: 6
Feature 2: 6

所以我想知道是否有人可以帮助我修改此命令以获得所需的输出或为我建议另一个命令? (P.S 原始文件包含数百个样本和大约 94 个特征)

【问题讨论】:

  • 为什么在if(/^\Feature/) 中的Feature 之前加上反斜杠?顺便说一句,永远不要使用字母 l 作为变量名,因为它看起来太像数字 1 并且会混淆您的代码。
  • @EdMorton 我在 awk 命令方面没有太多经验,在之前的帖子中建议使用此命令。感谢您对字母“l”的说明,我将避免使用它。

标签: bash awk


【解决方案1】:

你可以使用这个awk:

awk '/^Sample/{printf "%s%s",(c?c"\n":""),$0;c=0;next}
     /^Feature/{printf "%s\n%s: ",(c?c:""),$0;c=0;next}
     {c++}
     END{print c}' file

脚本只为不以SampleFeature 开头的行增加计数器c

如果找到 2 个关键字之一,则打印计数器。

【讨论】:

  • 非常感谢您的帮助和解释!该命令运行良好!
【解决方案2】:

这个awk 也可以工作:

awk '/^Sample/ {
   for (i in a)
      print i ": " a[i]
   print
   delete a
   next
}
/^Feature/ {
   f = $0
   next
}
{
   ++a[f]
}
END {
   for (i in a) 
      print i ": " a[i]
}' file

Sample1
Feature 1: 3
Feature 2: 4
Sample2
Feature 1: 3
Feature 2: 2

【讨论】:

  • 完美运行!感谢您的帮助!
【解决方案3】:
$ cat tst.awk
BEGIN { OFS = ": " }
/Sample/  { prtFeat(); print (NR>1 ? ORS : "") $0; next }
/Feature/ { prtFeat(); name=$0; next }
{ ++cnt }
END { prtFeat() }
function prtFeat() {
    if (cnt) {
        print name, cnt
        cnt = 0
    }
}

$ awk -f tst.awk file
Sample1
Feature 1: 3
Feature 2: 4

Sample2
Feature 1: 3
Feature 2: 2

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2023-03-07
    • 2022-08-04
    • 2017-02-02
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多