Sorting 3 columns and getting the average

2020-04-17 04:46发布

问题:

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

I get the following errors.

expr: non-integer argument

expr: syntax error

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.

I run the file like this:

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

This is the sample text.

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

回答1:

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.

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


标签: linux bash unix