在在Can you modify text files when committing to subversion?Grant建議我阻止承諾來代替。如何檢測文件以換行結束?
但是我不知道如何檢查以換行符文件結束。你怎麼能檢測到文件以換行符結束?
在在Can you modify text files when committing to subversion?Grant建議我阻止承諾來代替。如何檢測文件以換行結束?
但是我不知道如何檢查以換行符文件結束。你怎麼能檢測到文件以換行符結束?
@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 $1`
if [ "$c" != "" ]; then echo "no newline"; fi
你應該能夠通過SVN pre-commit鉤子來做到這一點。
這並沒有解決實際的問題,就是「你怎麼能檢測到文件結束換一個換行符?「 – 2014-03-12 23:51:26
你可以使用這樣的事情作爲您的預提交腳本:
#! /usr/bin/perl while (<>) { $last = $_; } if (! ($last =~ m/\n$/)) { print STDERR "File doesn't end with \\n!\n"; exit 1; }
只使用bash
:
(!注意正確複製空格)
@格羅姆:
尾不返回一個空行
該死。我的測試文件沒有在\n
上結束,而是在\n\n
上。顯然vim
無法創建不以\n
(?)結尾的文件。無論如何,只要「獲取最後一個字節」選項起作用,一切都很好。
或者更簡單:
#!/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'"
爲我工作:
tail -n 1 /path/to/newline_at_end.txt | wc --lines
# according to "man wc" : --lines - print the newline counts
所以wc計數換行數ars,這對我們來說很好。 根據文件末尾換行符的存在,oneliner打印0或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
+1簡單,有效,便攜。而不是perl。 :) – 2012-11-06 04:38:31
這個答案並不是最佳的,因爲我不知道你指的是哪個Konrad。 – oberlies 2014-12-23 15:40:48
不適用於我。 – Black 2016-01-22 09:36:23