LoginSignup
2
3

More than 5 years have passed since last update.

bash > 複数ファイルの2列目だけを平均化 > コメントに早いバージョンあり > awk の連想配列を使う方法を教えていただきました

Last updated at Posted at 2015-02-07

動作環境

CentOS 6.5

300個近くあるファイルの2列目だけを平均化したい。

in.001
0.0 3.14
1.0 2.71
2.0 6.022

などのファイルがin.001からin.300まで300個近くあるとする。
2列目(3.14, 2.71, 6.022)について全ファイルの平均を取りたい。

自分が作ったのは以下のスクリプト

avg_xxxfiles_exec
#!/bin/env bash

#numcol=$(cat $1 | awk 'END{print NF}')
numline=$(cat $1 | awk 'END{print NR}')

#echo $numline $numcol

for idx in $(seq 1 $numline)
do #idx
indat=""    
for infile in $(echo $@)
do #infile
cond="NR==$idx"
line=$(awk $cond $infile)
xxx=$(echo $line | awk '{print $1}')
work=$(echo $line | awk '{print $2}')
indat="$indat $work"
done # infile

avg=$(echo $indat | awk '{for(i=1;i<=NF;i++){sum+=$i}; print sum/NF}')
echo $xxx $avg
done # idx

以下のように実行すると平均化されたものが出力される。

$ bash avg_xxxfiles_exec in.*

問題はコーヒー1杯わかせるぐらい遅いこと。



(追記)
実際に使うスクリプトはheliac2000さんがコメントされたawkの処理を使うと良い。こちらは瞬時に結果が出せる。
2
3
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3