This is just an article that records a bit of knowledge, and this knowledge point is quite small. But I actually find it quite interesting, and I can handle it and explain it clearly.
Definition of a Line#
It all starts with a reminder like this, from git diff
, which I believe everyone has seen. \No newline at end of file
diff --git a/demo.py b/demo.py
index 8cde782..e75154b 100644
--- a/demo.py
+++ b/demo.py
@@ -1 +1 @@
-print("hello world")
+print("hello world")
\ No newline at end of file
Let me think about a question, why is it not subtracting a line but modifying the original last line. Why is there a distinction between print("hello world")\n
and print("hello world")
This actually involves the definition of a line in POSIX. (3.206 Line)
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
A line consists of a sequence of zero or more non-<newline>
characters, plus a terminating <newline>
character. Note the "plus" in this definition, which means that in the POSIX definition, a line must have a <newline>
as the ending. So, to be precise, the newline character is part of the terminating line, and a line without a newline character is not considered a line.
So in the above operation, I removed the \n
from the original complete line.
Potential Issues#
Therefore, as long as you follow the commands or software that comply with the POSIX standard, they will ensure that the end of a line is marked by \n
to be considered a true line. If the file does not end with a newline character, there may be issues in some cases.
Here, I will give an example of wc -l
:
My Solution#
- Tools like Vim and Nano will automatically add a blank line at the end when you save the file.
- VSCode extension: Automatically ensures the presence of a newline character at the end when you save the file.
- Linter plugins: You can install some linter plugins, such as pylint, which automatically adds a newline character when there is no newline character at the end.
- Shell script: Automatically add a newline character to all files in a directory if they do not have one at the end.
nini_ensure_newline(){ find . -type f | while read -r file; do if [ "$(tail -c 1 "$file")" != '' ]; then echo "Processing $file" echo "" >> "$file" fi done }
References#
- linux - 什么时候程序源码文件末尾要有空行?是怎么规定和考虑的 - SegmentFault 思否
Actually, the answers in this link are quite lonely, without recognizing the core of the POSIX standard. This matter is not related to the age of the software. Even new software can support the POSIX standard, which requires a newline character as the end of a line in order to consider it as a line. - How to force newline at end of files and why you should do it | by Alexey Inkin | Medium
It explains in detail, even including the explanation of the ending solution of my shell code. - missing-final-newline / C0304 - Pylint 3.0.0a8-dev0 documentation
Pylint also has a corresponding check item.