Linux-检查文件末尾是否有空行 [英] Linux - check if there is an empty line at the end of a file

查看:838
本文介绍了Linux-检查文件末尾是否有空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这个问题的措词以前是不同的,使用有/没有换行"而不是有/没有空行"

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

I have two files, one with an empty line and one without:

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

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

Is there a command or function to check if a file has an empty line at the end? I already found this solution, but it does not work for me. ( IGNORE: A solution with preg_match and PHP would be fine as well.)

推荐答案

在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>使其可执行):

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

这篇关于Linux-检查文件末尾是否有空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆