2007年11月5日 星期一

換行字元的轉換

換行字元的轉換

November 4th, 2007 by Chuan-Hsien Lin
Last Modified on November 4th, 2007

有時候我們可能在 Windows 環境的文件檔案,可能因為換行字元表示方式不同,而造成檔案在 Linux 底下會出問題。

例如,我在 Windows 用筆記本新增了一個 run.sh 的 Shell Script,內容只有四行如下,

#!/bin/sh

ls
pwd

但是,當我到 Cygwin 環境下,要執行該 Schell Script,結果就出現一堆錯誤訊息,

$./run.sh
./run.sh: line 2: $'\r': command not found
./run.sh: line 3: $'ls\r': command not found

這正是 Windows 換行字元表示方法跟 Unix 不同,而導致問題。此時,我們可以使用一個叫做 dos2unix 的小程式,可以幫我們把換行字元作轉換。

先來看一下轉換前的檔案內容,

$ od -t x1 run.sh
0000000 23 21 2f 62 69 6e 2f 73 68 0d 0a 0d 0a 6c 73 0d
0000020 0a 70 77 64
0000024

接著,使用 dos2unix 來轉換換行字元,

$ dos2unix run.sh
run.sh: done.

$ od -t x1 run.sh
0000000 23 21 2f 62 69 6e 2f 73 68 0a 0a 6c 73 0a 70 77
0000020 64
0000021

至此,可以看的出來,原本的換行字元 0d 0a 被改變成 0a 了,這支小程式倒是挺方便使用的,如此一來,剛剛不能執行的程式,就可以快樂的執行了。

相反的,如果要將 Unix 的換行字元轉換成 Windows 的換行字元,則使用 unix2dos 即可。

以下是 dos2unix 指令語法,節錄自 Cygwin。

$ dos2unix --help
dos2unix version 0.1.3
converts the line endings of text files from
DOS style (0x0d 0x0a) to UNIX style (0x0a)

Usage: dos2unix [OPTION...] [input file list...]

Main options (not all may apply)
-A, --auto     Output format will be the opposite of the 
               autodetected source format
-D, --u2d      Output will be in DOS format
--unix2dos     Output will be in DOS format
-U, --d2u      Output will be in UNIX format
--dos2unix     Output will be in UNIX format
--force        Ignore binary file detection
--safe         Do not modify binary files

Help options
-?, --help     Show this help message
--usage        Display brief usage message
--version      Display version information
--license      Display licensing information

Other arguments
[input file list...]   for each file listed, convert in place.
                       If none specified, then use stdin/stdout

沒有留言: