Linux - 检查文件末尾是否有空行[重复]

问题描述 投票:9回答:4

这个问题在这里已有答案:

注意:此问题的措辞不同,使用“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的解决方案也可以。)

linux eof carriage-return
4个回答
12
投票

在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

14
投票

只需输入:

cat -e nameofyourfile

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


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!

1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.