1

I have a text file that has a list of results from travel distance

Traveldistance.txt

12.1 meters
14.1 meters

Whenever I tried to compute the sum of the distance, the result will display this message

12.1
12.1
26.2
26.2

However, if I remove the word "meters" from the travel distance text file, it is able to compute perfectly, such as this

12.1
26.2

Is there any way to read in the string data and allow the distance to be computed perfectly, such as this

12.1 meters
26.2 meters

I have even tried while loop, but it did not even work. My codes are shown as below

#!/bin/bash

SUM=0;


for n in $(cat DistanceLog_TD01.txt)
do 
    SUM=$(echo "$SUM + $n" | bc); #Need help here
    echo $SUM;
        
done

echo $(date +"%m-%d-%Y %T") "Total distance:" $SUM "meters" >> totaldistance.txt

Thanks!

1

Use awk:

<infile awk '{ print sum+=$1, $2 }'

add date&time to the output:

<infile awk '{ print sum+=$1, $2 }
END{ print date_time }' date_time="$(date +'%F %T')"

note that the "date_time" above would be the date&time before command awk execution. if you need the date&time when awk finished the processing, do:

<infile awk '{ print sum+=$1, $2 }' && echo "$(date +'%F %T')"

or if you have GNU awk for the strftime() function:

<infile awk '{ print sum+=$1, $2 } END{ print strftime("%F %T") }'

see awk strftime() formatting here

to add date&time and output in one line:

<infile awk '{ sum+=$1 } END{ print sum, $2, date_time }' date_time="$(date +'%F %T')" 

again, you can use strftime() function for GNU awk to output date&time instead.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.