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

Bla*_*ack 10 linux carriage-return eof

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

文件:text_without_newline

$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#
Run Code Online (Sandbox Code Playgroud)

文件:text_with_newline

$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#
Run Code Online (Sandbox Code Playgroud)

是否有命令或函数来检查文件末尾是否有换行符?我已经找到了这个解决方案,但它对我不起作用.(编辑:IGNORE:使用preg_match和PHP的解决方案也可以.)

小智 15

只需输入:

cat -e nameofyourfile
Run Code Online (Sandbox Code Playgroud)

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


Fre*_*red 13

在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
}
Run Code Online (Sandbox Code Playgroud)

作为可以调用的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
Run Code Online (Sandbox Code Playgroud)