Dan
Dan

Reputation: 15

Missing last line in file

Using the code below. It will not copy the last line in the file.

I have tried the following means of reading the file.

"while IFS=$'\n' read -d '' -r -a myLine" or "while IFS=$'\n' read -r -a myLine"

while read -a myLine
do
  for ((i=0;i<"${#myLine[@]}";i++))
  do
    temp_array[$i]+=" ${myLine[$i]}"
  done
done < $1

File contains numbers like:

1 2
3 4
5 6

when echo is used to see what is in the array i get

1 2
3 4

this is where it drops off the last line.

Upvotes: 1

Views: 266

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125798

The problem is that on the last line, read hits the end of file rather an an end-of-line delimiter (newline character), so it returns a failure status and the loop exits. But it does put the content it read into the array variable, so check for that to make it process that last line:

while read -a myLine || [[ ${#myLine[@]} -gt 0 ]]
do

This is very similar to the solution for read without -a; the only difference is how to test for a nonempty line after the last linefeed.

Upvotes: 1

vintnes
vintnes

Reputation: 2030

Since Bash 4:

mapfile -t MyArray < "$1"

Upvotes: 1

Related Questions