Linux - check if there is an empty line at the end

2020-06-03 01:01发布

问题:

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

回答1:

In bash:

newline_at_eof()
{
    if [ -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 [ -z "$(tail -c 1 "$1")" ]
then
    echo "Newline at end of file!"
    exit 1
else
    echo "No newline at end of file!"
    exit 0
fi


回答2:

Just type:

cat -e nameofyourfile

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



回答3:

I found the solution here.

#!/bin/bash
x=`tail -n 1 "$1"`
if [ "$x" == "" ]; then
    echo "Newline at end of file!"
else
    echo "No Newline at end of file!"
fi

IMPORTANT: Make sure that you have the right to execute and read the script! chmod 555 script

USAGE:

./script text_with_newline        OUTPUT: Newline at end of file!
./script text_without_newline     OUTPUT: No Newline at end of file!


回答4:

The \Z meta-character means the absolute end of the string.

if (preg_match('#\n\Z#', file_get_contents('foo.txt'))) {
    echo 'New line found at the end';
}

So here you are looking at a new line at the absolute end of the string. file_get_contents will not add anything at the end. BUT it will load the entire file into memory; if your file is not too big, its okay, otherwise you'll have to bring a new solution to your problem.