如何检测换行符结尾?

时间:2020-03-05 18:46:13  来源:igfitidea点击:

结束于提交Subversion时可以修改文本文件吗?格兰特建议我改为阻止提交。

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

解决方案

回答

我们应该可以通过SVN预先提交钩子来执行此操作。

请参阅此示例。

回答

我们可以使用以下内容作为预提交脚本:

#! /usr/bin/perl

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

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

回答

仅使用bash

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

(请注意正确复制空白!)

@grom:

tail does not return an empty line

该死。我的测试文件不是在\ n上结束,而是在\ n \ n上结束。显然,vim不能创建不以\ n(?)结尾的文件。无论如何,只要获取最后一个字节选项有效,就可以了。

回答

@Konrad:尾部不返回空行。我制作了一个文件,该文件的文本不以换行符结尾,而一个文件则包含换行符。这是tail的输出:

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

$ cat test_with_newline.txt
this file ends in newline
$

虽然我发现尾巴有最后一个字节选项。因此,我将脚本修改为:

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

回答

甚至更简单:

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

但是,如果我们想要更强大的检查:

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