Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EOL character missing from file on Linux

I have a file that does not have an EOL at the end of the last line. I noticed this when my bash script that reads from it was not processing the last line.

I read from it like this:

while read LINE
do
    ...
done <thefile

The file is supplied to me, and so there is nothing I can do to it before it lands on my system (Linux - OpenSuSE 10.2). I do run dos2unix on the file, but that does not resolve the missing EOL.

I have seen a couple of solutions involving vi and ed, but they are a bit clunky and I was hoping there is a neater solution, maybe using sed, that I can use from within my bash script?

Oddly, when I vi the file and do a :set list, I can see a "$" at the end of the last line. I was expecting that to be missing as I thought that "$" represented \n. Or maybe there is a difference between newline and end-of-line?

like image 521
user265330 Avatar asked Nov 20 '25 18:11

user265330


1 Answers

Here's an option to add a newline to the end of the file if it doesn't already have one (and isn't blank):

if [ -s "$thefile" ] && [ "$(tail -c1 "$thefile"; echo x)" != $'\nx' ]; then
    echo >>"$thefile"
fi

Alternately, here's an easy way to modify the loop to process anything after the final newline:

while read LINE || [ -n "$LINE" ]
do
...
like image 152
Gordon Davisson Avatar answered Nov 23 '25 10:11

Gordon Davisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!