Created
December 11, 2012 19:01
-
-
Save MikeDacre/4261078 to your computer and use it in GitHub Desktop.
Change number of spaces used for indentation in a file, only change spaces at start of file. Made for python, will work with any file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
#=============================================================================== | |
# | |
# FILE: change_indent_length.py | |
# | |
# USAGE: cange_indent_length.py [-h] file_name old_tab_length new_tab_length | |
# | |
# DESCRIPTION: Change indent length, only change those at start of line | |
# | |
# AUTHOR: Michael D Dacre, [email protected] | |
# ORGANIZATION: Stanford University | |
# LICENSE: CC BY-NC-SA - Creative Commons Attribution-NonCommercial-ShareAlike | |
# VERSION: 0.3 | |
# CREATED: 11-12-12 09:42:14 | |
#=============================================================================== | |
import sys | |
import argparse | |
import re | |
# Get command line arguments | |
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, | |
description="""\ | |
Change indent length, only effect those spaces at start of line. | |
Will write new file out as original file name with '_tabbed' appended""") | |
parser.add_argument('file_name', type=str, help="Filename of file to parse") | |
parser.add_argument('old_tab_length', type=int, help="The current length of tabs in the file") | |
parser.add_argument('new_tab_length', type=int, help="The new length for tabs in the output file") | |
args = parser.parse_args() | |
file_name = args.file_name | |
old_tab_length = args.old_tab_length | |
new_tab_length = args.new_tab_length | |
# Create regex | |
split = re.compile( '^([ ]*)([^ ].*)$' ) | |
spaces = re.compile( ''.join( [ '([ ]{', | |
str(old_tab_length), | |
'})' | |
] ) | |
) | |
f = open(file_name, 'r') | |
o = open('_'.join([file_name, 'tabbed']), 'w') | |
for line in f: | |
split_line = split.search(line).groups() | |
tabs = spaces.findall(split_line[0]) | |
# Error checking | |
if len(split_line) != 2: | |
raise Exception("split_line regex failed! split_line does not contain two elements") | |
new_tabs = [] | |
# Loop through tabs | |
for tab in tabs: | |
t = [] | |
# Use new_tab_length to create new_tabs | |
count = new_tab_length | |
while(count): | |
t.append(' ') | |
count = count - 1 | |
new_tabs.append(''.join(t)) | |
print(''.join([''.join(new_tabs), split_line[1]]), file=o) | |
f.close() | |
o.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment