A simple text search and replace program.
Python, 24 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
#!/usr/bin/env python import os, sys usage = "usage: %s search_text replace_text [infile [outfile]]" % os.path.basename(sys.argv) if len(sys.argv) < 3: print usage else: stext = sys.argv rtext = sys.argv input = sys.stdin output = sys.stdout if len(sys.argv) > 3: input = open(sys.argv) if len(sys.argv) > 4: output = open(sys.argv, 'w') for s in input.xreadlines(): output.write(s.replace(stext, rtext)) # For older versions of Python (1.5.2 and earlier) import # the string module and replace the last two lines with: # # for s in input.readlines(): # output.write(string.replace(s, stext, rtext))
Perhaps this is too simple to be included as a cookbook entry, but it's a frequently asked question. Maybe teachers will stop assigning it as a homework problem. ;-)
Slight Mods. This code as is will not work. The main problem is that the output file object is not closed, so nothing actually gets written to the file. Also xreadlines is not a method of the file object (at least not in Jython, where I tested this). Anyway, give this one a go:
xreadlines is deprecated. Since xreadlines is deprecated the solution should look like this:
None of these work. Actually, all of these examples are wrong, s is not defined anywhere in the script and the replace method requires 3 arguments.
Actually. You are wrong... s is declared in the for loop where it is used, and the third argument to replace is optional.
great recipe, it has been years since I did Python so I appreciate it!