2011年11月30日 星期三

Linux和Windows的換行字元

Linux和Windows所使用的換行字元是不一樣的
在Windows底下是使用\r\n (0x0D 0x0A)
在Linux底下是使用\n (0x0A)

因此如果你把Windows上建立的文件搬到Linux上用editor看的話
會在每一行的最後面看到一個 '^M' 的字元
這是因為Linux的換行字元只有\n,因此會把\r給印出來

這點可以做個簡單的實驗來觀察
sway:~/tmp$ ls
hello_linux  hello_windows.txt
hello_linux是在Linux產生出來的檔案
hello_windows.txt是在Windows產生出來的檔案
之後我們用od把ascii dump出來看
sway:~/tmp$ od -c hello_windows.txt
0000000   h   e   l   l   o  \r  \n
0000007

sway:~/tmp$ od -c hello_linux
0000000   h   e   l   l   o  \n
0000006
可以發現Linux下是使用\n當換行字元
而Windows是使用\r\n

這些多出來的'^M'有時後會造成程式的錯誤
當我們把檔案從Windows搬到Linux底下有沒有什麽解決方法呢?
有一些方法,解決方法如下:

1.
dos2unix [-kn] filename [new filename]
sway:~/tmp$ dos2unix -k -n hello_windows.txt new_hello_windows
2. 在Vim下輸入指令,用Regular Expression把\r取代掉
 :%s/\r//g  
3. 用tr把\r給清掉
cat filename | tr -d '\r' > new filename
sway:~/tmp$ cat hello_windows.txt | tr -d '\r' > new_hello_windows

沒有留言:

張貼留言