如何计算bash中一列数据中的连续重复次数?

问题描述 投票:0回答:4

如果我有一个很长的文本文件,如下所示:

A
A
B
B
A
A
A
B
A
A
B
A
...

我想找到'A'的数量连续(例如1,2,3 ......),然后报告每个序列中有多少个。

所以上面的代码片段会给我3:1,2:2:1:1,其中第一个数字是顺序'A'的数字,第二个数字是这些序列中有多少出现在整个文件中。

这可能在bash / awk / sed等吗?

我尝试使用awk来计算实例数:

awk ' BEGIN {count=0;}  { if ($1 == "A") count+=1} end {print $count}'

但我不知道如何获得序列长度的信息。

bash awk sed
4个回答
2
投票

在一个命令中:

awk '/A/{c++;next}
     c{a[c]++;c=0}
     END{if(c){a[c]++}
         for(i in a) {print i":"a[i]}
     }' <file>
  • /A/{c++;next}如果该行包含A增加计数器c并移动下一行
  • c{a[c]++; c=0}如果cZERO不同,增加存储在c中的a[c]的频率,并将c设置为ZERO
  • END打印频率。

1
投票

Awk解决方案:

awk '{ if ($1 == "A") { k++ } else if (k) { a[k]++; k=0 } }
     END{ if (k) a[k]++; for (i in a) print i ":" a[i] }' file

输出:

1:1
2:2
3:1

1
投票

一条非awk管道

$ uniq -c file | grep A | sort -r | 
  rev | uniq -c | rev | sed 's/ A /:/;s/  *//g' | paste -sd,

3:1,2:2,1:1

1
投票
< your_file \
  uniq -c | # count the number of occurrences in a row
  awk '$2 == "A" { print $1 }' | # keep only the counts of “A” (and not the “A” themselves)
  sort | # sort the counts
  uniq -c | # count the number of occurrences of each count
  awk '{ print $2 " " $1 }' | # swap the count of count and the count
  sort -nrk1 | # sort by count, numerically, decreasing
  tr ' ' : # use a colon as separator instead of a space

输出:

3:1
2:2
1:1
© www.soinside.com 2019 - 2024. All rights reserved.