banner
niracler

niracler

长门大明神会梦到外星羊么?
github
email
steam_profiles
douban
nintendo switch
tg_channel
twitter_id

Why files should end with a newline character, and how we should ensure it.

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:

image

My Solution#

  1. Tools like Vim and Nano will automatically add a blank line at the end when you save the file.
  2. VSCode extension: Automatically ensures the presence of a newline character at the end when you save the file.
    image
  3. 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.
  4. 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#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.