排序3列并获取平均值 [英] Sorting 3 columns and getting the average

查看:102
本文介绍了排序3列并获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行testing.sh文件时

when I run my testing.sh file

#!/bin/bash
FILE=$1
COUNT=0
while read -r SID FIRST LAST S1 S2 S3 
do
    SUM=$(expr $S1 + $S2 + $S3)
    AVG=$(expr $SUM / 3)
    printf '%d [%d] %s, %s\n' "$AVG" "$SID" "$LAST" "$FIRST"
done < "$FILE" | sort -k 3,3n -k 4,4n -k 2,2g

我遇到以下错误.

expr: non-integer argument

expr: syntax error

我不确定自己在做什么错.我也尝试了echo,awk和bc,但所有这些我都遇到了类似的错误.

I'm not sure what I'm doing wrong. I also tried echo, awk, and bc but I got similar errors for all of them.

我这样运行文件:

/testing.sh/home/user/Desktop/sample.txt

/testing.sh /home/user/Desktop/sample.txt

这是示例文本.

123456789 Lee Johnson 72 85 90
999999999 Jaime Smith 90 92 91
888111818 JC Forney 100 81 97
290010111 Terry Lee 100 99 100
199144454 Tracey Camp 77 84 84
299226663 Laney Camp 70 74 71
434401929 Skyler Camp 78 81 82
928441032 Jess Forester 85 80 82
928441032 Chris Forester 97 94 89

运行程序时,应为输出:

When I run my program, this should be the output:

71 [299226663] Camp, Laney
80 [434401929] Camp, Skyler
81 [199144454] Camp, Tracey
93 [928441032] Forester, Chris
82 [928441032] Forester, Jess
92 [888111818] Forney, JC
82 [123456789] Johnson, Lee
99 [290010111] Lee, Terry
91 [999999999] Smith, Jaime

推荐答案

您的S3实际上不包含诸如90的值,而是包含诸如90$'\r'的值,因为您的输入文件具有CRLF( DOS(而不是LF(UNIX)换行符).如果您是从非UNIX系统获得输入文件的,则通常会发生这种情况.

Your S3 does not actually contain a value such as 90, but instead contains values such as 90$'\r', because your input file has CRLF (DOS) rather than LF (UNIX) newlines. This most often happens if you got your input file from a non-UNIX system.

使用dos2unix或vim命令:set fileformat=unix之类的工具修复文件,或在脚本中使用类似于以下代码的代码:

Fix the file, using tools such as dos2unix or the vim command :set fileformat=unix, or use code akin to the following in your script:

S3=${S3%$'\r'} # remove any trailing $'\r' from S3

这篇关于排序3列并获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆