我如何判断我的编辑器是否在差异文件的末尾添加或删除了换行符?

How can I tell if my editor is adding or removing newlines at the end of a file from the diff?

如果我有以下差异:

diff --git a/file.txt b/file.txt
index abcdef..ghijkl mnopqr
--- a/file.txt
+++ b/file.txt
@@ -2,4 +2,4 @@

-This is a line of code.
\ No newline at end of file
+This is a line of code

我明白I want the newline at the end of the file。但是,从这个差异来看,我的编辑器是在文件末尾添加还是删除了换行符?

我无法判断 \No newline at end of file 是指我的文本编辑器删除的内容(上方)还是添加的内容(下方)。

您的问题中引用的消息表明换行符已添加到正在比较的文件的较新版本中。

如果换行符在比较新版本的文件中被删除,您会看到:

diff --git a/file.txt b/file.txt
index abcdef..ghijkl mnopqr
--- a/file.txt
+++ b/file.txt
@@ -2,4 +2,4 @@
-This is a line of code.
+This is a line of code.
\ No newline at end of file

也就是说,\ No newline at end of file 部分将是差异的最后一行。


如果您想自己测试,可以在 运行 diff -u 上找到两个文件:

  • noeol.txt(文件末尾没有换行符)
  • eol.txt(文件末尾有一个换行符)

diff -u noeol.txt eol.txt 会给你这个:

--- noeol.txt   2016-08-13 12:55:16.000000000 +0900
+++ eol.txt 2016-08-13 12:55:23.000000000 +0900
@@ -1 +1 @@
-This is a line of code.
\ No newline at end of file
+This is a line of code.

diff -u eol.txt noeol.txt 会给你这个:

--- eol.txt 2016-08-13 12:55:23.000000000 +0900
+++ noeol.txt   2016-08-13 12:55:16.000000000 +0900
@@ -1 +1 @@
-This is a line of code.
+This is a line of code.
\ No newline at end of file