如何将文件中的一行放入表中(变量)

时间:2019-06-03 10:16:12

标签: bash shell

我有以下文件

Durand 12 9 14
Lucas 8 11 4
Martin 9 12 1

我需要用功能显示其他三个名称和平均值。功能部分很简单。

我认为我可以逐行获得:

head -i notes | tail -1

然后将命令的结果放在表中以便访问

table=(head -i notes | tail -1)
echo "${table[0]} averge : moy ${table[1]} ${table[2]} ${table[3]}"

1 个答案:

答案 0 :(得分:0)

您可能会使用三个重要的概念来解决这样的问题。

  1. 遍历文件
  2. 将值存储为变量
  3. 对变量进行数学运算

逐行读取文件的一种好方法是使用while循环:

while read line; do echo $line; done < notes

请注意我们如何使用文件重定向<将文件视为标准输入。 read一次消耗一整行。让我们对其进行扩展以存储单独的变量。

while read name a b c; do echo $name $a $b $c; done < notes

现在让我们参与数学。您可以使用bc之类的外部程序,但是如果我们不需要浮点数学运算(小数),那么效率很低。 Bash内置了数学运算法则!

while read name a b c; do echo $name $(( (a + b + c) / 3 )); done < notes

就像你说的那样,功能部分很简单:)


找一个班轮:

awk '{print $1, ($2+$3+$4)/3}' notes