Skip to content

Instantly share code, notes, and snippets.

@Rast1234
Created May 7, 2014 13:09
Show Gist options
  • Select an option

  • Save Rast1234/7a9d787167f720711e10 to your computer and use it in GitHub Desktop.

Select an option

Save Rast1234/7a9d787167f720711e10 to your computer and use it in GitHub Desktop.
line-endings counter and converter (when you have mixed LF and CRLF in one file)
#!/usr/bin/python
import sys
from subprocess import call
def main():
if len(sys.argv) == 3 and sys.argv[1] == "-c":
filename = sys.argv[2]
(all, dos, nix) = doWork(filename)
cmd = "unix2dos" if dos > nix else "dos2unix"
call([cmd, "-q", "-k", filename])
elif len(sys.argv) == 2:
filename = sys.argv[1]
data = doWork(filename)
print "all {} dos {} unix {}".format(*data)
else:
#print help
help()
def doWork(filename):
with open(filename, 'r') as infile:
data = infile.read()
return count(data)
def count(data):
all = data.count("\n")
dos = data.count("\r\n")
nix = all - dos
return (all, dos, nix)
def help():
print "Count line endings in file: DOS and UNIX"
print "Usage: line-endings [-c] filename"
print " -c converts to DOS/UNIX format according to majority of line-endings of that kind"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment