The following is short, uses several python libraries,
illustrates writing a filter and using flags so its good for
learning Python. I think you may have changed the regexp library
since my copy of Python so we might want to change the function
names appropriately.
Lou Kates, louk@research.teleride.on.ca
# swap fields x and y preserving whitespace; skip lines with too few fields
# eg: python swapcols.py -x 2 -y 3 myfile.dat
import getopt, regexp, string, sys
options, files = getopt.getopt(sys.argv[1:], 'x:y:')
x, y = 1, 2
for (flag, value) in options:
if 'x' in flag: x = string.atoi(value)
if 'y' in flag: y = string.atoi(value)
if x > y: x, y = y, x
fp = sys.stdin
if files: fp = open(files[0], 'r')
while 1:
line = fp.readline()
if not line: break
if len(string.split(line)) >= y:
t = (regexp.compile('[ \t]*([^ \t]+)' * y)).exec(line)
(a, b), (c, d) = t[x], t[y]
line = line[:a] + line[c:d] + line[b:c] + line[a:b] + line[d:]
print line[:-1]