Regex search and replace

Another random task that I find myself doing distressingly often: performing a regular expression search and replace recursively across a bunch of files. You can do this relatively directly with tools like sed, but I can never quite remember the particularly flavor of regular expression syntax sed uses.

So instead, here’s a version that uses Python regular expressions:

#!/usr/bin/env python

import re
import sys

if len(sys.argv) < 3:
	print('Usage: re {pattern} {replacement} [file(s)]')

in_place_mode = '-i' in sys.argv
if in_place_mode: sys.argv.remove('-i')

pattern, replacement = sys.argv[1:3]
files = sys.argv[3:]
if not files: files = ['-']

for file in files:
	if file == '-':
		fin = sys.stdin
		fin = open(file, 'r')

	text =

	text = re.sub(pattern, replacement, text)

	if in_place_mode:
		fout = open(file, 'w')
		fout = sys.stdout


	if in_place_mode:

Quick and simple. It will open the file, read it in, replace, and save it back out. One neat trick is that you can read from stdin / write to stdout all relatively transparently.

As with all of my dotfiles, you can see the entire source on GitHub: re.

comments powered by Disqus