结束于 提交颠覆时可以修改文本文件吗? 授予 建议我改为阻止提交。

但是我不知道如何检查文件以换行符结尾。如何检测文件以换行符结尾?

有帮助吗?

解决方案

@康拉德: :tail 不返回空行。我创建了一个文件,其中包含一些不以换行符结尾的文本和一个以换行符结尾的文件。这是 tail 的输出:

$ cat test_no_newline.txt
this file doesn't end in newline$ 

$ cat test_with_newline.txt
this file ends in newline
$

虽然我发现 tail 有获取最后一个字节的选项。所以我将你的脚本修改为:

#!/bin/sh
c=`tail -c 1 $1`
if [ "$c" != "" ]; then echo "no newline"; fi

其他提示

或者更简单:

#!/bin/sh
test "$(tail -c 1 "$1")" && echo "no newline at eof: '$1'"

但如果您想要更可靠的检查:

test "$(tail -c 1 "$1" | wc -l)" -eq 0 && echo "no newline at eof: '$1'"

这是一个有用的 bash 函数:

function file_ends_with_newline() {
    [[ $(tail -c1 "$1" | wc -l) -gt 0 ]]
}

您可以像这样使用它:

if ! file_ends_with_newline myfile.txt
then
    echo "" >> myfile.txt
fi
# continue with other stuff that assumes myfile.txt ends with a newline

您可以使用类似这样的内容作为预提交脚本:

#! /usr/bin/perl

while (<>) {
    $last = $_;
}

if (! ($last =~ m/\n$/)) {
    print STDERR "File doesn't end with \\n!\n";
    exit 1;
}

为我工作:

tail -n 1 /path/to/newline_at_end.txt | wc --lines
# according to "man wc" : --lines - print the newline counts

所以 wc 计算换行符的数量,这在我们的例子中很好。oneliner 根据文件末尾是否存在换行符打印 0 或 1。

仅使用 bash:

x=`tail -n 1 your_textfile`
if [ "$x" == "" ]; then echo "empty line"; fi

(注意正确复制空格!)

@格罗姆:

tail 不返回空行

该死。我的测试文件没有结束于 \n 但在 \n\n. 。显然 vim 无法创建不以以下结尾的文件 \n (?)。不管怎样,只要“获取最后一个字节”选项有效,一切都很好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top