I am doing a project for my university, and this is the first time I'm coding using Bash.
I am trying to go trough a .txt document, reading every line, and taking the information I need to make a sum.
The .txt document looks something like this:
83210:Henrique Gaspar:EIB2:911235444:[email protected]:carro:BMW:82-RX-14:5:25:26 88110:Vasco Rapido:IB2:962222222:[email protected]:mota:BMW:33-MT-99:3:5:16 88020:Maria Aguiar:EIB2:911555444:[email protected]:carro:mercedes:88-TX-11:2:20:12
And for what I am doing I need to make the total sum of last number of each user, so 26+16+12.
Now, here is my code:
#!/bin/bash
echo -n "Nº de condutores: "
echo $(cat condutores.txt | wc -l)
echo -n "Nº de passageiros: "
echo $(cat passageiros.txt | wc -l)
echo -n "Saldo total dos condutores: "
x=0
linhas=$(cat condutores.txt | wc -l)
i=0
while [[ $i -le $linhas ]]; do
sum=$(cat condutores.txt | head -$i | tail -$(( $linhas + 1 - $i )) | cut -d':' -f11)
x=$((x+sum))
i=$((i+1))
done
echo "$x"
I wrote it in full here so nothing gets missed out.
What matters for the problem here is from line 7 to 15. I don't know if it is the way I am going through each line of the condutores.txt file or any other thing. But I am getting this error:
Saldo total dos condutores: ./stats.sh: line 12: 26
16: syntax error in expression (error token is "16")
26
So for some reason it only reads the first and second line of the .txt document, but can't make the sum, can anyone help me here please? Thanks in advance.
Your $sum contains more than one line, so it cannot be interpreted as number. And your text processing loop is a nightmare, there is a more cleaner solution. Look:
x=0
while IFS=: read -r a b c d e f g h i j k; do
x=$((x+k))
done < condutores.txt
echo "$x"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With