如何計算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

相關內容