How do I print all complete lines of a file? By 'complete' I mean only the ones that end with newline character. grep treats EOF as line delimiter, so grep '^.*$' file will print the last line even if there's no newline at the end of file.

The whole problem comes from parsing log files: we need to somehow be sure that the last entry was completely logged - i.e. it ends with newline.


2 Answers 2


A simple approach is to use perl:

perl -ne '/\n/ && print' file

If you just want to check that the last character of a file is a newline, you can do:

tail -c1 file | grep -q '^$' && echo yes || echo no

But the -c option is not POSIX, so it isn't portable.


read (at least in Bourne shell) requires a line to be terminated with newline:

# /bin/sh -c 'echo -e "foo\nbar\c" | while read line; do echo $line; done'

So you could use something like:

while read line
    do echo $line
done < logfile.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .