Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux - check if there is an empty line at the end of a file [duplicate]

NOTE: this question used to be worded differently, using “with/out newline” instead of “with/out empty line”

I have two files, one with an empty line and one without:

File: text_without_empty_line

$root@kali:/home#cat text_without_empty_line
This is a Testfile
This file does not contain an empty line at the end
$root@kali:/home#

File: text_with_empty_line

$root@kali:/home#cat text_with_empty_line
This is a Testfile
This file does contain an empty line at the end

$root@kali:/home#

Is there a command or function to check if a file has an empty line at the end? I already found this solution, but it does not work for me. (EDIT: IGNORE: A solution with preg_match and PHP would be fine as well.)

like image 423
Black Avatar asked Jan 22 '16 09:01

Black


People also ask

How do I search for a blank line in a file?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use an extended regular expression like ' a^ ' or ' $a '.

Why is there an empty line at the end of a file?

The empty line in the end of file appears so that standard reading from the input stream will know when to terminate the read, usually returns EOF to indicate that you have reached the end. The majority of languages can handle the EOF marker.


2 Answers

Just type:

cat -e nameofyourfile

If there is a newline it will end with $ symbol. If not, it will end with a % symbol.

like image 69
Camila Masetti Avatar answered Sep 17 '22 13:09

Camila Masetti


Olivier Pirson's answer is neater than the one I posted here originally (it also handles empty files correctly). I edited my solution to match his.

In bash:

newline_at_eof()
{
    if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
    then
        echo "Newline at end of file!"
    else
        echo "No newline at end of file!"
    fi
}

As a shell script that you can call (paste it into a file, chmod +x <filename> to make it executable):

#!/bin/bash
if [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]
then
    echo "Newline at end of file!"
else
    echo "No newline at end of file!"
fi
like image 33
Fred Avatar answered Sep 17 '22 13:09

Fred