Linux - 检查文件末尾是否有空行

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

注意:这个问题以前的措辞不同,使用“with/out换行符”而不是“with/out空行”

我有两个文件,一个有空行,一个没有:

文件: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#

文件: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#

有没有命令或函数可以检查文件末尾是否有空行? 我已经找到 this 解决方案,但它对我不起作用。 (编辑:忽略:使用 preg_match 和 PHP 的解决方案也可以。)

\Zmeta-character表示字符串的绝对结束

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

所以在这里您看到的是字符串绝对末尾的新行。 file_get_contents 不会在最后添加任何内容。但是它会将整个文件加载到内存中;如果您的文件不是太大,没关系,否则您将不得不为您的问题带来新的解决方案。

Olivier Pirson's answer 比我最初发布在这里的那个更整洁(它也能正确处理空文件)。我编辑了我的解决方案以匹配他的。

在bash中:

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

作为您可以调用的 shell 脚本(将其粘贴到文件中,chmod +x <filename> 使其可执行):

#!/bin/bash
if [[ -s "" && -z "$(tail -c 1 "")" ]]
then
    echo "Newline at end of file!"
else
    echo "No newline at end of file!"
fi

我找到了解决方案 here

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

重要提示:确保您有权执行和阅读脚本! chmod 555 script

用法:

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

只需输入:

cat -e nameofyourfile

如果有换行符,它将以$符号结束。 如果不是,它将以 % 符号结尾。