Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created January 29, 2016 15:50
Show Gist options
  • Save amoilanen/59e00f6129725e9b4404 to your computer and use it in GitHub Desktop.
Save amoilanen/59e00f6129725e9b4404 to your computer and use it in GitHub Desktop.
Python script to replace tabs with spaces recursively for all files matching a specified file mask regex, the number of spaces if configurable
#
# Usage:
#
# python tabs2spaces.py . 2 .*\.js$
#
import argparse
import os
import re
parser = argparse.ArgumentParser(description='Replace tabs with spaces.')
parser.add_argument('root_directory', type=str, default='.', nargs='?',
help='directory to run the script in')
parser.add_argument('spaces_for_tab', type=int, default=2, nargs='?',
help='number of spaces for one tab')
parser.add_argument('file_mask_regex', default=".*", nargs='?',
help='file name mask regex')
args = parser.parse_args()
file_mask_regex = re.compile(args.file_mask_regex)
replacement_spaces = ' ' * args.spaces_for_tab
print('Starting tab replacement. \
directory {0}, spaces number {1}, file mask {2}'.format(args.root_directory, args.spaces_for_tab, args.file_mask_regex))
found_files = []
for path, subdirs, files in os.walk(args.root_directory):
for name in files:
found_files.append(os.path.join(path, name));
matched_files = [name for name in found_files if file_mask_regex.match(name)]
for file_path in matched_files:
file_contents = ''
with open(file_path) as f:
file_contents = f.read()
file_contents = re.sub('\t', replacement_spaces, file_contents)
print('Replacing tabs in {0}'.format(file_path))
with open(file_path, "w") as f:
f.write(file_contents)
print('Done')
@zchrissirhcz
Copy link

@jcwii Sorry that I made my repo private since I thought my implementation is not very elegant(and using clang-format is an alternantive).. Now it is public again

My comment saying "not perfectly equal", an examle would demonstrate what that mean:

    std::cout   << "hello world" << endl;

In this example line, there are 4 spaces before std::cout, this is the same when specify tabsize=4. However, there are 3 spaces between std::cout and << when you type tab right after std::cout, instead of 4, thus replacing it with 4 spaces would make it not match the original meaning of table symbol.

@jcwii
Copy link

jcwii commented Jan 30, 2021

@zchrissirhcz the explanation and efforts are both very kind of you. Thank you Zhuo Zhang.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment