LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Reading numbers from text file and storing in array (https://www.linuxquestions.org/questions/linux-general-1/reading-numbers-from-text-file-and-storing-in-array-810224/)

idaham 05-26-2010 09:46 AM

Reading numbers from text file and storing in array
 
2 Attachment(s)
Dear all!

I'm writing a bash script where I read a text file (containing a column of numbers) and store each line in an array. There seem to be some problems with the whole thing however, but only for some files and not others. Here's what I do:
Code:

#!/bin/bash
file=time_notOk.txt ### The file with a column of numbers
i=0 ### Array counter

### Read the file
exec 3<$file

### Loop over each line of the file and store in array
while read value <&3
do
        array[$i]=$value       
        echo test1 ${array[$i]} test2       
        i=$(($i+1))
done

Running this I get the echo output (from the loop):
Code:


 test20
 test21
 test22
 test23
 test24
 test25
 test26
...

Apparently something's wrong! When I read another file however, just the same but with other numbers in it, it works and I get the output as it should be:
Code:

test1 0 test2
test1 10 test2
test1 20 test2
test1 30 test2
test1 40 test2
test1 50 test2
test1 60 test2
...

I've attached the two text files. Is there something wrong with my input files or the code? Thanks!
Ida

catkin 05-26-2010 10:06 AM

time_notOk.txt has DOS/Windows line ends on all but the last line. These can be seen in vi or using the od command. Fix by, for example, using fromdos command.

idaham 05-27-2010 01:50 AM

Dear catkin,
Thank you so much for your reply! You're a lifesaver! I ran the dos2unix (fromdos) command and converted my files and now it's working properly... Thank you!
Ida

Quote:

Originally Posted by catkin (Post 3981843)
time_notOk.txt has DOS/Windows line ends on all but the last line. These can be seen in vi or using the od command. Fix by, for example, using fromdos command.


catkin 05-27-2010 03:36 AM

Glad it solved the problem for you :)

Threads can be marked SOLVED via the Thread Tools menu.


All times are GMT -5. The time now is 10:14 PM.