Replace newlines with literal \n

后端 未结 6 1595
北荒
北荒 2020-12-05 17:17

This stackoverflow question has an answer to replace newlines with sed, using the format sed \':a;N;$!ba;s/\\n/ /g\'.

This works, but not for special characters like

6条回答
  •  一个人的身影
    2020-12-05 17:39

    Here is little python script for replacing the '\r\n' with '\r' in directory in a recursive way import os import sys

    if len(sys.argv) < 2:
        print("Wrong arguments. Expected path to directory as arg 1.")
        exit(1)
    
    path = sys.argv[1]
    
    
    def RecOpOnDir(path, op) :
        for f in os.listdir(path):
            full_f = path + "/" + f
            if os.path.isdir(full_f):
                RecOpOnDir(full_f, op)
            else:
                try:
                    op(full_f)
                except Exception as ex:
                    print("Exception during proc '", full_f, "' Exception:", ex)
    
    file_counter = 0
    
    def WinEndingToUnix(path_to_file):
        global file_counter
        file_counter += 1
        file_strs = []
        with open(path_to_file) as f:
            for line in f:
                file_strs.append(line.replace(r"\r\n", r"\n"))
    
        with open(path_to_file, "w") as fw:
            fw.writelines(l for l in file_strs)
    
    try:
        RecOpOnDir(path, WinEndingToUnix)
        print("Completed.", file_counter, "files was reformed")
    except Exception as ex:
        print("Exception occured: ", ex)
        exit(1)
    

提交回复
热议问题