原文:http://blogmag.net/blog/read/136/Convert_text_files_from_DOS_to_UNIX_and_vice_versa
周海漢 /譯
注:本文是簡譯。
dos/windows的純文本回車換行,即/r/n,記爲CRLF,16進製爲0d0a,Unix/Linux是/n,16進製爲0a, 記爲LF, mac爲/r, 0a。
下面主要講將/r/n 轉爲unix的/n的方法。
$ file dosfile.txt
dosfile.txt: ASCII text, with CRLF line terminators
$ file unixfile.txt
unixfile.txt: ASCII text
使用tr
$ tr -d '/r' < dosfile.txt > unixfile.txt
使用vim
$ vim dosfile.txt
...
:set FileFormat = unix
可以用:set FileFormat=dos 來轉爲dos格式。簡寫爲FF。可以:help Fileformat來查看幫助。
使用emacs
set-buffer-file-encoding-system 函數設置coding-system。
M-x set-buffer-file-coding-system Unix
使用sed
$ sed 's/.$//' dosfile.txt > new_unixfile.txt
將unix轉dos格式
$ sed 's/$' "/`echo -e " /r "`/" unixfile.txt > new_dosfile.txt
新版gnu sed:
$ sed 's/$//r/' unixfile.txt > new_dosfile.txt
使用perl
$ perl -p -e 's//r$//' < dosfile.txt > new_unixfile.txt
$ perl -p -e 's/$//r/' < unixfile.txt > new_dosfile.txt
使用awk
$ awk '{sub("/r$", "", $0);print $0}' dosfile.txt > new_unixfile.txt
$ awk '{sub("$", "/r", $0);print $0}' unixfile.txt > new_dosfile.txt
使用python
$ python -c "import sys; map(sys.stdout.write, (l[:-2] + '/n' for l in sys.stdin.readlines()))" < dosfile.txt > new_unixfile.txt
還有其他的方法。對大文件,建議用sed,awk,perl,python,不建議用vi,emacs.