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

时间:2016-01-22 09:50:26

标签: linux eof carriage-return

注意:这个问题的措辞不同,使用“with / out newline”而不是“with / out empty line”

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

文件: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解决方案,但它对我不起作用。 (编辑:IGNORE:使用preg_match和PHP的解决方案也可以。)

4 个答案:

答案 0 :(得分:14)

只需输入:

cat -e nameofyourfile

如果有换行符,则会以$符号结尾。 如果没有,它将以%符号结尾。

答案 1 :(得分:11)

在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
}

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

#!/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 :(得分:2)

我找到了解决方案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

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

用法:

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

答案 3 :(得分:1)

\Z元字符表示字符串的绝对结尾。

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

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

相关问题