天天看點

Linux換行符和Windows換行符的差別與轉換

不同系統文本檔案的行尾換行符不同:

  1. Windows為一個回車’\r’(CR或^M)和一個換行’\n’(NL或LF)(括号内是其它顯示方法)
  2. Linux為一個換行’\n’
  3. Mac為一個回車’\r’

檢視檔案是否含有Windows換行符:

  1. Windows:Notepad++ ==>視圖 ==>顯示所有符号
  2. Linux:file test.txt

    test.txt: ASCII text, with CRLF line terminators

  3. Vim:指令模式下輸入:e ++ff=unix,^M就是Windows換行符

轉換方法:

  1. Windows下Notepad++ ==>編輯 ==> 文檔格式轉換 ==> 轉為Unix
  2. Linux:

    sed -i 's/\r//' filename

  3. Linux:

    dos2unix filename

    (需要先安裝dos2unix)

dos2unix文法:

dos2unix [-hkqV] [-c convmode] [-o file …] [-n infile outfile …]

參數說明:
-k:保持輸出檔案的日期不變
-q:安靜模式,不提示任何警告資訊。
-V:檢視版本
-c:轉換模式,模式有:ASCII, 7bit, ISO, Mac, 預設是:ASCII。
-o:寫入到源檔案
-n:寫入到新檔案
           
  1. Linux批量轉換:

    find -type f | xargs dos2unix -o

  2. Vim:指令模式下輸入

    :%s/^M//g

    或者

    :g/\^M/s/\^M//

  3. Vim:指令模式輸入

    :set ff?

    如果出現fileforma=dos 表示是Windows上的換行符。繼續輸入

    :set fileformat=unix

    儲存即可

繼續閱讀