Skip to content
Advertisement

Bash: While-read loop skips the last line of comma-separated text file

I am trying to read some comma-separated data from a text file, parse it and calculate average of column-5. The input is in the following form:

Computer ID,User ID,M,T,W,T,F
Computer1,User3,5,7,3,5,2
Computer2,User5,8,8,8,8,8
Computer3,User4,0,8,0,8,4

I am using the following script for this:

hours = 0
while IFS=, read -r col1 col2 col3 col4 col5 col6 col7
do
((hours = hours + col5))
echo "$col1, $col2"
done < <(tail -n+2 user-list.txt)
echo "$hours"

The problem with the script is that it does not read / parse the last line of the text. What can I do about that?

Also, every time I run the script, the value of hours keeps on increasing (probably the previous value is stored). How can the value be defaulted to zero everytime the script runs?

TIA

Advertisement

Answer

The following code worked for me:

hours=0
#echo "n" >> user-list.txt
while IFS=, read -r col1 col2 col3 col4 col5 col6 col7 || [[ -n $col1 ]]
do
    ((hours = hours + col5))
    #echo "$col1, $col2"
done < <(tail -n+2 user-list.txt)

((hours = hours/10))
echo "$hours"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement