0

I have a simple text file that contains a single serial number in every line. The last serial of the file is often (but not always) not followed by a '\n' character. Here is an example of such file:

$ cat input.txt
323114853
358018893
208829592

And here are the exact bytes:

$ od -c -b input.txt

0000000   3   2   3   1   1   4   8   5   3  \n   3   5   8   0   1   8
        063 062 063 061 061 064 070 065 063 012 063 065 070 060 061 070
0000020   8   9   3  \n   2   0   8   8   2   9   5   9   2
        068 071 063 012 062 060 070 070 062 071 065 071 062
0000035

Here is my bash script that tries to read the serials from the text file:

$ cat go.sh
while IFS='' read -r SERIAL
do

    echo ${SERIAL}

done < input.txt

But fails to read that last serial:

$ ./go.sh
323114853
358018893

Surely there has to be some simple fix, though I can't seem to get it right. Any help is very much appreciated, thanks!

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • 2
    The last character of the file needs to be a newline `\n` for `read` to interpret EOF. To fix it add a condition `read -r SERIAL || [ -n "$SERIAL" ];` – Inian Nov 01 '18 at 08:28
  • @Inian thanks for the quick fix. I understand that the question is indeed a duplicate, but IMHO it's more concise and explicit here than in the original post. Anyway I glad you pointed out this quick fix here too. – OrenIshShalom Nov 01 '18 at 08:36
  • @OrenIshShalom: Glad you found it useful. The only reason I duped it, the answers in the duplicated question are more authoritative. Leaving yours open here, has a chance to attract poorly formatted/incorrect and/or vague answers – Inian Nov 01 '18 at 08:41

0 Answers0