Search code examples
bashbash4

bash: iterating through txt file lines can't read last line


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

Solution

  • 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.