[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Memo: tab2space - expand tabs in string by one or more spaces



 
    
tab2space - expand tabs in string by one or more spaces:

[root@igloo LDAPExplorer-devel]# cat tab2space.sh 
#!/bin/sh

# Replace tabs with whitespace in each line
# '^t' represents a true tab character. Under bash or tcsh, 
# press Ctrl-V then Ctrl-I.
sed 's/ /    /g' $1 > $2


[root@igloo LDAPExplorer-devel]# cat tab2space.py 
#! /usr/bin/env python

# "tab2space" expand tabs in a string, replace them by one or more spaces, depending 
# on the current column and the given tab size. This doesn't understand other 
# non-printing characters or escape sequences.

import sys
import string
import getopt

try:
    opts, args = getopt.getopt (sys.argv[1:], 'i:o:t:')
except getopt.error, msg:
    sys.stdout = sys.stderr
    # print msg
    print "usage:", sys.argv[0], "-i inputfile -o outputfile -t tabsize"
    sys.exit (2)
  
inflag = 0
ouflag = 0
tabflag = 0
for o, value in opts:
    if o == '-i':
        inflag = 1
        infile = value
    if o == '-o':
        ouflag = 1
        oufile = value
    if o == '-t':
        tabflag = 1
        tabsize = string.atoi (value)
if not (inflag and ouflag and tabflag):
    sys.stdout = sys.stderr
    print "usage:", sys.argv[0], "-i inputfile -o outputfile -t tabsize"
    sys.exit (2)

try:
    infp = open (infile, 'r')
except IOError, msg:
    # sys.stderr.write ("%s: can't open (%s)\n" % (file, msg))
    sys.stderr.write ("can't open file %s\n" % infile)
    sys.exit (2)
try:
    oufp = open (oufile, 'w')
except IOError, msg:
    sys.stderr.write ("can't open file %s\n" % oufile)
    sys.exit (2)

aline = infp.readline ()
while aline != '':
    newline = string.expandtabs (aline, tabsize)
    oufp.write (newline)
    aline = infp.readline ()

infp.close ()
oufp.close ()


Google