
我不是 UNIX 愛好者,但對 UNIX 的理解足以到處編寫小腳本,除了這個,我個人可能無法投入足夠的時間。
我的目錄中有大約 2000 個文件,需要對其執行以下操作:
- 每個檔案大約有 3000 筆記錄,但所有記錄都在每個檔案的一行上,並用 Ctrl M 換行符號分隔。這些需要分開。
- 每個檔案在第一行中從第 8 個字元到第 14 個字元都有對應的生成日期。需要使用此日期將檔案重新命名為 XXX_YYYYMMDD_AAA.txt
答案1
大多數系統都包含一個名為「gin up」的工具dos2unix
,您可以在腳本中「gin up」該工具來處理執行此操作所需的檔案。
如果這些檔案都在一個目錄中,您可以使用find
它來定位它們,然後分別對每個檔案進行操作,如下所示:
$ find . -type f -exec dos2unix {} +
例子
假設我有這個目錄結構
$ tree
.
|-- afile
|-- dir1
| `-- afile
`-- dir2
`-- afile
我們可以使用我們的find
技術來確認所有檔案都是帶有 CRLF 行終止符的「DOS」檔案。
$ find . -type f -exec file {} +
./dir2/afile: ASCII text, with CRLF line terminators
./afile: ASCII text, with CRLF line terminators
./dir1/afile: ASCII text, with CRLF line terminators
並像這樣修復所有內容:
$ find . -type f -exec dos2unix {} +
dos2unix: converting file ./dir2/afile to Unix format ...
dos2unix: converting file ./afile to Unix format ...
dos2unix: converting file ./dir1/afile to Unix format ...
只產生 Unix 檔:
$ find . -type f -exec file {} +
./dir2/afile: ASCII text
./afile: ASCII text
./dir1/afile: ASCII text