zl程序教程

您现在的位置是:首页 >  系统

当前栏目

Linux 基础命令(01): dos2unix 搞定 Linux 和 Windows 换行符的噩梦

LinuxWindows基础命令 搞定 01 换行符 噩梦
2023-06-13 09:17:20 时间

Linux 基础命令(01): dos2unix 搞定 Linux 和 Windows 换行符的噩梦

大家好, 我是老麦 原文链接: https://tangx.in/posts/2022/12/28/dos2unix-and-unix2dos/

不同操作系统 换行符 标准不统一, 秦始皇听了都要落泪。 多少年前, 我曾也被这东西坑过无数次, 往事不堪回首。

事情是这样的, 今天群里面一个朋友被换行符坑了。

windows-newline-ifs

看到这个问题, 我依旧一身冷汗。

不同操作系统的 换行符

不同操作系统采用不同的换行符:

  1. Linux: \n
  2. Windows: \r\n
  3. Mac OS X
    • 老系统: \r
    • 新系统: \n

dos2unix 拯救一切

dos2unix 是一组命令集合, 可以在 mac,linux,windows 之间相互转换换行符。

ubuntu 系统为例, 安装命令如下

$ sudo apt -y install dos2unix

安装之后, 你将得到 这些命令

# ls -al /usr/bin/ | grep unix 
-rwxr-xr-x 1 root root     51288 Aug 16  2021 dos2unix
lrwxrwxrwx 1 root root         8 Aug 16  2021 mac2unix -> dos2unix
-rwxr-xr-x 1 root root     51288 Aug 16  2021 unix2dos
lrwxrwxrwx 1 root root         8 Aug 16  2021 unix2mac -> unix2dos

名字非常直观。

换行符是不可见字符

换行符是不可见字符, 在 Linux 中, 可以通过命令 cat -A 查看

$ cat demo.txt 
my name is zhangsan     # 换行符不可见

$ cat -A demo.txt 
my name is zhangsan$    # 注意尾部结尾是 $

可以确认, cat -A 尾部是 $ 符号。这个符号并不是我们文件中的可见字符。

使用 unix2dos 换行为 Windows 换行符

# unix2dos
$ unix2dos demo.txt 
unix2dos: converting file demo.txt to DOS format...

$ cat -A demo.txt 
my name is zhangsan^M$  # 注意尾部结尾是 ^M$


# dos2unix
$ dos2unix demo.txt 
dos2unix: converting file demo.txt to Unix format...

$ cat -A demo.txt 
my name is zhangsan$

使用 file 查看换行符

使用 file 命令, 可以更直观查看文件使用的换行符。

$ dos2unix demo.txt 
$ file demo.txt  # linux
demo.txt: ASCII text


$ unix2dos demo.txt 
$ file demo.txt  # windwos
demo.txt: ASCII text, with CRLF line terminators


# 追加 Linux 换行符
$ echo 1231232 >> demo.txt 
$ cat -A demo.txt 
my name is zhangsan^M$
1231232$

## 查看结果
$ file demo.txt 
demo.txt: ASCII text, with CRLF, LF line terminators

可以看到, 经过 dos2unix 转换前后, file 命令结果所有不同,

  1. 如果是 Linux 换行符, 没有提示。
  2. 如果是 Windows 换行符结果有 CRLF 的提示。
  3. 如果是混合换行符, 提示 CRLFLF 都存在。

真的很棒。