如何计算unix中文件中跨行的平均列数以及最大列数?

如何计算unix中文件中跨行的平均列数以及最大列数?

我有一个文件看起来像:

1
2 4 5 6 7 19
20
22
24 26 27 
29 30 31 32 34 40 50 56 58
234 235 270 500
1234 1235 1236 1237
2300

考虑到我的真实数据文件很大。所以我想检查这个数据文件中的最大数量是多少。我还想检查行中平均存在多少列。作为这个小示例中的示例,最大列数为 9(第 5 行),行内平均有 3.33 列。有什么建议吗?

答案1

$ awk 'NF > m { m = NF } { s += NF } END { printf("Max = %d\nAvg = %g\n", m, s/NR) }' data.in
Max = 9
Avg = 3.33333

awk脚本将跟踪 中的最大字段(列)数m以及 中的字段数总和s。当到达输入流的末尾时,它将输出收集到的统计信息。

当前记录(行)的字段数为NF,目前已读取的记录数为NR

以下版本还将跟踪字段数最多的记录:

awk 'NF > m { m = NF; r = NR } { s += NF } END { printf("Max = %d (%d)\nAvg = %g\n", m, r, s/NR) }' data.in
Max = 9 (6)
Avg = 3.33333

答案2

您可以使用“dc”实用程序进行数学工作:

dc -e "
[zsmlksn]sb
[lk1+skzls+ss]sa
[[Max = ]nlmn[(]nlnn[)]n10an[Avg = ]n5klslk/1/n10an]sp
[lpxq]sq
[?z0=qlaxzlm<bcl?x]s?
0ddddsksmsnssd=?
"

下面显示了上述内容的工作原理

tr '\t-' ' _'  data.in | # dc wants negative numbers to begin with underscores
dc -e "
[
   z sm  # store current num of cols in register "m"
   lk sn # store row num in register "n"
]sb

[
   lk 1 + sk # increment the number of rows
   z ls + ss # add num of cols to running sum of cols
]sa

[
   [Max=]n
   lmn             # put max number of cols on ToS & print it
   [(]n
      lnn          # put row num at which max number of cols are present on ToS & print it
   [)]n
   10an

   [Avg=]n
     5k ls lk /1/n  # accuracy of 5 digits, compute average = sum of cols / total num of cols
   10an

]sp

[
   lpx # print the results by invoking the macro "p"
   q   # quit
]sq

# while loop for reading in lines
[
   ? z 0 =q # quit when no columns found in the current line read in
   lax      # macro "a" does: rows++, sum+=cols
   z lm <b  # update max cols value stored in register "lm" when cols > lm
   c        # clear out the line and read in the next line
   l?x      # read the next line
]s?

# initializations+set the ball rolling:
# register "sk" -> line kount
# register "sm" -> max cols
# register "sn" -> row number corresp. to max cols
# register "ss" -> sum of cols

0
  d  d  d  d
  sk sm sn ss
d=?
"

结果

Max = 9(6)
Avg = 3.33333

相关内容