关于回车换行符

目录

术语

回车(Carriage Return, CR, ASCII 13, 通常表示为\r)
换行(Line Feed, LF, ASCII 10,通常表示为\n)

默认值

对于文本文件,Windows默认换行符号为CRLF,类unix系统(Linux,Mac OS 10+)是LF

git中的显示与设置

git diff 中出现的^M符号是回车,即Carriage Return, CR

core.autocrlf是git中的一个设置,支持在不同情况下对换行符自动做转换:

  • Windows中的推荐设置为true,这样它会在add/commit时自动将CRLF转换为LF,checkout时自动将LF转为CRLF
  • Linux/Mac中的推荐设置为input,这样它会在add/commit时自动将CRLF转换为LF,checkout时不做任何转换
  • 如果git repo的使用人开发部署都在同一种操作系统中,那可以设置为false,这样它不会做任何转换

除了用git config进行相对全局的设置,也可在Repo级别用.gitattributes文件来指定特定后缀文件的换行符。比如想在checkout时让*.sh文件的换行符号永远为LF,不管在Windows还是Linux/Mac,可以这样设置:

# Declare files that will always have LF line endings on checkout.
*.sh text eol=lf

查询文件换行符

Windows上查看文件换行符的工具太多,我就不列举了,win11连自带的notepad都支持,更不用说NotePad++和VS Code。在只能SSH连接的Linux系统中,如何查看某文本文件的换行符呢?目前知道的可以用以下工具:

file命令

如果file命令检测到文本不是以UNIX标准的LF符号为换行符,将会在命令结果中报告。例如:

ReadMe.txt: ISO-8859 text, with CRLF line terminators

od命令

od -c 可打印文本中所有字符,包括隐藏字符,例如 od -c my_file.py |head -50 结果为

0000000    i   m   p   o   r   t       o   s  \r  \n   i   m   p   o   r
0000020    t       d   a   t   e   t   i   m   e  \r  \n  \r  \n   #
0000040   从  **  **  生  **  **  产  **  **  环  **  **  境  **  **  导
0000060   **  **  出  **  **  数  **  **  据  **  **  到  **  **   S   3
0000100   的  **  **  脚  **  **  本  **  **  \r  \n   d   e   f       g
0000120    e   t   _   p   r   o   _   s   c   r   i   p   t   (   )   :
0000140   \r  \n                   s   c   r   i   p   t       =       "

从以上结果中可以看到好几处\r\n,所以换行符号为CRLF。

python对文本换行符的处理

python读写文本文件存在自动处理规则,依平台而不同,读文件到字符串时统一显示为\n,写文件时只需指定\n,python会自动将其转换为平台特定的换行符。文档原文:

In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n. When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.