﻿# 用懷念的 UNIX2DOS 與 DOS2UNIX 批次轉換檔案 (跨平台)

每次從 Linux 搬檔案到 Windows 或是將檔案從 Windows 搬移到 Linux 下都有可能會需要轉換不同的換行字元，由於 Linux 下慣用的換行字元是 \\n 而在 Windows 下卻是 \\r\\n，所以經常會有一些莫名的問題發生，例如用 Notepad 開啟 \\n 斷行的檔案就會全部亂成一團，而在 Linux 底下也偶爾會遇到些問題，這時我們就可以再傳檔之前先將檔案轉換過即可，這時也需要依賴一些工具幫我們做轉換。

若要在 Windows 下做格式轉換，可以下載 DOS2UNIX and UNIX2DOS for Windows 工具程式回來使用，你可以透過 DOS 模式 (命令提示字元) 執行批次檔 ( \*.bat ) 指令或使用 [PowerShell](http://en.wikipedia.org/wiki/Windows_PowerShell) 即可針對整個目錄包含子目錄進行檔案格式的轉換，指令如下：

**DOS 版：DOS2UNIX - 將 CRLF ( \\r\\n ) 轉換成 LF ( \\n )**

```
for /f %f IN ( 'dir /b /s *.php *.htm *.html *.css *.js' ) DO @dos2unix %f
```

**DOS 版：UNIX2DOS - 將 LF ( \\n ) 轉換成 CRLF ( \\r\\n )**

```
for /f %f IN ( 'dir /b /s *.php *.htm *.html *.css *.js' ) DO @unix2dos %f
```

**PowerShell 版：DOS2UNIX - 將 CRLF ( \\r\\n ) 轉換成 LF ( \\n )**

```
foreach ( $file in dir -include ('*.php', '*.htm', '*.html', '*.css', '*.js') -recurse){    dos2unix $file.FullName}
```

**PowerShell 版：UNIX2DOS - 將 LF ( \\n ) 轉換成 CRLF ( \\r\\n )**

```
foreach ( $file in dir -include ('*.php', '*.htm', '*.html', '*.css', '*.js') -recurse ){    unix2dos $file.FullName}
```

雖然從上述的語法來看，Powershell 比命令提示字元下的指令還多，但是直覺多了，而且所有取得的物件都有型別的概念。另一個需要注意的是，無論 PowerShell 或 DOS 版都使用 dir 來取得檔案清單，但是在 PowerShell 下的 dir 只是 [Get-ChildItem](http://technet.microsoft.com/en-us/library/dd347686.aspx "http://technet.microsoft.com/en-us/library/dd347686.aspx") 的一個別名而已，並非執行 DOS 下的 dir 指令。

如果要在 Ubuntu Linux 下執行，還必須先安裝 tofrodos 套件才行：

```
apt-get install tofrodos
```

在 Linux 底下可以使用 find 命令搭配一些參數使用，也可以做到整個目錄包含子目錄所有相關檔案的轉換功能：

```
find . -type f \( -name '*.php' -o -name '*.htm*' -o -name '*.css' \) -exec dos2unix -v '{}' \;
```

為了排版美觀，以上指令我將 \*.js 給移除，總之這只是個範例看懂了再用即可。在使用 find 指令時有兩個重點需提醒：

1.  使用 **\-name** 的時候若有萬用字元要用 單引號 ( ‘ ) 框起來，否則容易發生以下錯誤：

```
find: paths must precede expressionUsage: find [-H] [-L] [-P] [path...] [expression]
```

3.  多組 **\-name** 之間要用 **\-o** 組合起來，這裡的 –o 是邏輯運算子 OR ( 或 ) 的意思。
4.  使用 **\-exec** 時，最後一個參數必須是 **\\;** 才會正常執行，這是初學者常犯錯誤的地方。

**相關連結**

-   DOS2UNIX and UNIX2DOS for Windows \[直接下載\]
-   [How to write a DOS batch file to loop through files](http://jamesewelch.wordpress.com/2008/05/01/how-to-write-a-dos-batch-file-to-loop-through-files/)
-   [Get-ChildItem](http://technet.microsoft.com/en-us/library/dd347686.aspx "http://technet.microsoft.com/en-us/library/dd347686.aspx")
-   [Advanced techniques for using the UNIX find command](http://www.ibm.com/developerworks/aix/library/au-unix-find.html)
-   [Linux or Unix find and remove files with one find command on fly](http://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/)
-   [A Unix/Linux “find” Command Tutorial](https://web.archive.org/web/20150406053730/http://content.hccfl.edu:80/pollock/Unix/FindCmd.htm)
