Why should text files end with a newline?

后端 未结 18 1641
栀梦
栀梦 2020-11-21 22:56

I assume everyone here is familiar with the adage that all text files should end with a newline. I\'ve known of this \"rule\" for years but I\'ve always wondered — why?

18条回答
  •  不要未来只要你来
    2020-11-21 23:33

    It's very late here but I just faced one bug in file processing and that came because the files were not ending with empty newline. We were processing text files with sed and sed was omitting the last line from output which was causing invalid json structure and sending rest of the process to fail state.

    All we were doing was:

    There is one sample file say: foo.txt with some json content inside it.

    [{
        someProp: value
    },
    {
        someProp: value
    }] <-- No newline here
    

    The file was created in widows machine and window scripts were processing that file using PowerShell commands. All good.

    When we processed same file using sed command sed 's|value|newValue|g' foo.txt > foo.txt.tmp

    The newly generated file was

    [{
        someProp: value
    },
    {
        someProp: value
    

    and boom, it failed the rest of the processes because of the invalid JSON.

    So it's always a good practice to end your file with empty new line.

提交回复
热议问题