0

I am having some difficulty understand why i'm not able to enter my while read j loop. The goal of my program is to enter files 1-5 and calculate the sum of the numbers in each file. The output i'm getting is showing me that the read j line is executed, however the while loop isn't entered. This doesn't make intuitive sense to me, since the while condition would be true if the line is read. Heres the output, and the snippet of program below:

in for loop
file1
in for loop
1 9 6 3 3 6
file2
in for loop
1 3 7 6 4 4
file3
in for loop
1 4 8 8 2 4
file4
in for loop
1 5 9 9 1 7
file5

Code:

for (( n=0;n<$columns;n++ ))
do
    echo "in for loop"
    echo $j
    filename="file$counter"
    echo "$filename"
    #while reading line from current file, take the numbers and find the sum
    while read j
    do
        echo "in while loop"
        for number in $j
        do
            sum=$(($sum + $number))
        done
        echo "Sum: $sum"
    done < $filename
    counter=$(($counter + 1))
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jamanji
  • 11
  • 3
  • 2
    I suspect your file doesn't end in a newline. `read` sets the variable to the contents of the line, but has non-zero exit status. See http://stackoverflow.com/questions/4165135/how-to-use-while-read-bash-to-read-the-last-line-in-a-file-if-there-s-no-new – Barmar Oct 06 '16 at 20:00
  • 1
    Your code doesn't seem to match your output, or something very weird is going on with the value of `j`. Your output shouldn't be able to contain "in for loop" immediately followed by "file1"; there should at the very least be a blank line between the two (if `j` doesn't have a value yet). – chepner Oct 06 '16 at 20:09
  • OR was you data file created or passed thru MS windows environment? If so then you have `\r\n` lineendings. Use `dos2unix myDataFile` to convert it to just `\n` which is appropriate for unix/linux. Good luck. – shellter Oct 06 '16 at 20:34
  • 1
    @barmar Your answer was right, inserted newline characters into the last file and it worked :) – Jamanji Oct 06 '16 at 21:10

1 Answers1

0

Solution: Add a newline character to the end of the line in each file, read looks for the newline character to recognize a line.

Jamanji
  • 11
  • 3