bash: iterating through txt file lines can't read last line [duplicate]
Asked Answered
M

3

5

This code can read all lines in the file.txt except the last line any ideas why.

while read p; do
  echo $p
done < file.txt
Miscreant answered 18/5, 2013 at 18:27 Comment(0)
M
9

If you're in doubt about the last \n in the file, you can try:

while read p; do
    echo "$p"
done < <(grep '' file.txt)

grep is not picky about the line endings ;)

You can use grep . file.txt for skipping empty lines.

Melicent answered 18/5, 2013 at 18:50 Comment(0)
C
7

Well last line does not contain the newline character, as the other answers have pointed out. But the read command actually sets the p variable, and then instead of returning a success, returns an end of file error. So this error stops the loop from getting executed. You can still use the p variable which contains the last line from the file

while read -r p || [[ -n "$p" ]]
do
    echo "$p"
done < file.txt

This puts 2 conditions to be tested, as with or, only if the first fails, the second gets executed. So, when the last line will cause an end of file error in read, we will check if the p is set or not. If yes, we will use that.

Chavers answered 18/5, 2013 at 19:4 Comment(0)
B
3

cat file.txt and see if the very last line has a new line at the end of the last line or not. If it does not then while read p ; do echo "$p"; done < file.txt won't echo the last line put a new-line at the end of the last line in the text file.

Berber answered 18/5, 2013 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.