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

夙愿已清 提交于 2019-12-03 07:14:54

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
Camila Masetti

Just type:

cat -e nameofyourfile

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

Black

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!