Welcome, guest | Sign In | My Account | Store | Cart

expand_tabs.py - Similar to Unix's expand(1) command, but can edit the files in-place.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
import fileinput, optparse, sys

# Command-line parser
parser = optparse.OptionParser(
        usage="""
%prog [options] [files]
Expand tab to spaces, printing to the standard output by default.
When no files are given, read from the standard input.

Examples:
 expand in one file
    % expand_tabs.py -t 4 file.txt

 expand tabs in Python source files
    % find . -name "*.py" | xargs expand_tabs.py -it 4
""".strip(),
        formatter=optparse.IndentedHelpFormatter(max_help_position=30)
    )
parser.add_option("-t", "--tabsize", type="int", metavar="SIZE")
parser.add_option("-i", "--inplace", action="store_true", help="change the files in-place (don't print)")
parser.add_option("-b", "--backupext", default="", metavar="EXT", help="backup extension to use (default: no backup)")

options, args = parser.parse_args()
if options.tabsize is None:
    parser.error("tab size not specified")

# Do the work
for line in fileinput.input(files=args, inplace=options.inplace, backup=options.backupext):
    sys.stdout.write( line.expandtabs(options.tabsize) )

Sadly, expand(1) doesn't support in-line replacement, so this is a humble alternative.

The option parsing takes most of the code because this is meant as an actual utility, but all the real work is in module 'fileinput' and the 'expandtabs' string method.