如何在bash中以列方式读取文本文件中的表

时间:2015-04-13 09:52:18

标签: bash

我是新手来编写脚本,今天我已经处理了一个问题,我通常在python中做。问题是我有一个文本文件,如下所示:(行中的数字由制表符分隔)

1   1   1   1   1
9   3   4   5   5
6   7   8   9   7
3   6   8   9   1
3   4   2   1   4
6   4   4   7   7

现在我编写了一个bash脚本,它逐行读取并计算行的行平均值和中值。现在我想计算列平均值和列中位数。我怎么能这样做我发现很难从列中读出来。 我不想使用awk 这是我的代码:

#! /bin/bash
clear
if [ "$#" -eq 0 ]; then
    echo "Please provide arguments"
elif [ "$#" -lt 2 ]; then
     echo "You have to provide 2 arguments"
elif [ "$#" -gt 2 ]; then
    echo "You have provided more number of arguments"
else
    echo "You have entered correct number of arguments"
fi
option="${1}" 
case ${option} in 
   -rows| -r) FILE="${2}"
      echo "rows" 
      echo "File name is $FILE"
      clear
      echo "Average Median"
      while read -r line
      do
      len=0
      tot=0
      name=$line
      IFS=' ' read -a array <<< "$name"
      for element in "${array[@]}"
      do
          tot=$(expr $tot + $element)
          #let tot+=$element #you can use this as well to get the totals
          let len+=1
      done
      avg= printf "%.0f" $(echo "scale=2;$tot/$len" | bc)
      readarray -t sorted < <(for a in "${array[@]}"; do echo "$a"; done | sort)
      no=`expr $len % 2`
      if [ $no -eq 0 ]; then
      mid=`expr $len / 2`
      echo "$avg   ${sorted[$mid]}"
      else
      mid=`expr $len / 2`
      echo "$avg   ${sorted[$mid]}"
      fi
      unset "array[@]"
      unset "sorted[@]"
      done < "$FILE"
      ;; 
   -cols| -c) FILE="${2}" 
      echo "cols"
      echo "File name is $FILE"
      while read line
      do
      x=1
      read -a array <<< "$line"
      for element in "${!arra[@]}"
      do
      row[${element}] = $((${row[${element}]}+${array[$element]}))
      ((x++))
      done
      done < "$FILE"
      for element in ${row[@]}
      do
      mean=$(echo "$element/$x" bc -l)
      echo "$element / $x = $mean"
      done
      ;; 
   *)  
      echo "`basename ${0}`:usage: [-r|-rows rows] | [-c|-cols columns]" 
      exit 1 # Command to come out of the program with status 1
      ;; 
esac 

Can anyone help me with this please

1 个答案:

答案 0 :(得分:1)

使用bash获得平均值比获得中位数要容易得多。也许是这样的:

for ((i=1;i<=$(head -1 test.txt | wc -w);i++)) do
  echo "$(echo $(($(cut -f${i} test.txt | tr "\n" "+" )0)))/$(wc -l < test.txt)" | bc -l
done

以下是我发现使用bash查找中位数的示例: https://cs.fit.edu/~mmahoney/cse4001/median.bash.txt

  

该程序计算命令中整数列表的中位数   线。如果没有参数,则它会要求用户输入它们   分开的。然后它打印中位数(中间值后   排序)。如果有偶数个数字,则中位数为   2个中间值的平均值,向下舍入

如果您使用上述相同的cut方法搜索可以轻松遍历列的位置,还有其他一些较短的示例。