處理Windows文件格式爲Linux文件格式的方法

本文將介紹處理Windows文件格式爲Linux文件格式的3種方法。

1 判斷Windows文件格式

在Linux系統中,當我們執行shell腳本時,有時會出現以下錯誤:

[root@master test]# sh t.sh
t.sh: line 2: $'\r': command not found
hello world

該錯誤的原因就是腳本文件爲Windows文件格式,我們可以通過使用vi -b <file>查看是否爲Windows文件格式。即

[root@master test]# vi -b t.sh
#!/bin/bash^M
^M
echo "hello world"

在該文件的一行結束位置有^M字符,表示該文件爲Windows文件格式,如何批量的將Windows文件格式轉換爲Linux文件格式呢?下面介紹3種處理方法。

2 處理Windows文件格式爲Linux文件格式的方法

1 Linux sed命令處理

[root@master test]# find . -type f -print0|xargs -0 -I{} sed -i -e "s/\r//g" {}

2 linux dos2unix命令處理

[root@master test]# find . -type f -print0|xargs -0 -I{} dos2unix {}

3 python處理

下面的python程序將處理指定目錄下以postfixes列表中結尾的文件,將匹配文件中tab替換成4個空格,且修改文件格式爲unix格式。

import os

lineList = []
postfixes = ['.py', '.java', '.c', '.cpp', '.h']

def deal_lines(file_name):
    cmd = "dos2unix -ascii %s" %file_name
    os.system(cmd)
    with open(file_name, 'r') as f:
        for line in f:
            str = line.replace('\t', '    ').rstrip()
            yield str + "\n"

def format_covert(file_path):
    for path, dirs, files in os.walk(file_path):
        for name in files:
            full_path = os.path.join(path, name)
            norm_path = os.path.normpath(os.path.abspath(full_path))
            modifyFileFlag = any([norm_path.endswith(postfix) for postfix in postfixes])
            if modifyFileFlag:
                for line in deal_lines(norm_path):
                    lineList.append(line)
                with open(norm_path, 'w+') as f:
                    for index in range(0, len(lineList)):
                        f.write(lineList[index])
                del lineList[:]

if __name__ == '__main__':
    file_path = raw_input('Please input a file path: ')
    format_covert(file_path)

3 總結

由於sed命令是linux系統內置命令,而dos2unix命令默認情況下是不帶的,需要安裝後才能使用,因此建議使用sed命令進行處理。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章