Simple New Line Converter – CRLN DOS<=>UNIX,换行符替换工具脚本

作者:半瓶墨水   链接:http://www.2maomao.com/blog/simple-new-line-converter-crln-dosunix/

svn/hg下来的文件经常是unix换行符的,为了其他的脚本处理方便,我都统统转为dos的
以前东西少,手动就行了,gvim里面:set ff=dos就行,这次太多了,就写了个脚本

Python语言: Simple New Line Converter – CRLN DOS<=>UNIX,换行符替换工具脚本
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple New Line Converter for CR-LN of DOS & UNIX format
#  default convert known text files under current folder
#
# by 半瓶墨水 ( realfun at gmail dot com )
# http://2maomao.com/blog/
import os
import sys

newline = "\r\n"
if len(sys.argv) > 1 and sys.argv[1] == 'unix':
    newline = "\n"

#only convert files with the following extention
#NOTICE: spaces on HEAD/END are there on purpose!
exts = ' py html css js json txt php ini cpp h sql ini htm rb cmd bat '
fs = []
#for root, dirs, files in os.walk('d:/projects/py/django/fayaa'):
for root, dirs, files in os.walk('.'):
    for f in files:
        f = os.path.join(root, f)
        #print "==>" + f
        pos = f.rfind('.')
        if pos == 1:
            continue
        if exts.find(' ' + f[pos+1:] + ' ') != 1:
            fs.append(f)

for f in fs:
    o = open(f, "r")
    ls = o.readlines()
    o.close
    if len(ls):
        print ">>", f
        o = open(f, "wb")
        #NOTICE: here I did what I want, remove ".rstrip()" if you don't like it!
        ls = [l.rstrip() + newline for l in ls]
        for l in ls:
            o.write(l)
        o.close()

2 条评论 发表在“Simple New Line Converter – CRLN DOS<=>UNIX,换行符替换工具脚本”上

  1. RedNax说道:

    其实有更简单的办法吧,如果是linux下面的话,一般有两个小工具,一个叫dos2unix,一个叫unix2dos,记得是用来转化回车的管道。
    Windows下面的话,既然用vim就可以直接用vim结合for进行批处理操作

    for %a in (*) do vim -e -s –noplugin -c “set ff=dos” -c wq %a

    当然上面vim可以换成gvim

  2. 半瓶墨水说道:

    @RedNax
    恩,应该有这样的工具
    多谢你提供的信息,vim高级指令我现在还不是很熟

    呵呵够用就行啊

留下回复