Skip to content

Instantly share code, notes, and snippets.

@samuel
Created May 17, 2011 00:17
Show Gist options
  • Save samuel/975645 to your computer and use it in GitHub Desktop.
Save samuel/975645 to your computer and use it in GitHub Desktop.
Regular expression search and replace as an OS X service
#!/usr/bin/env python
import re
import sys
import subprocess
def osascript(script):
p = subprocess.Popen("osascript", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
stdout = p.communicate(script)[0]
if p.returncode != 0:
return None
return stdout
def quote(text):
return text.replace('"', r'\"')
def dialog(title, question):
return osascript("""
tell application "Finder"
activate
set Input to display dialog "{question}" with title "{title}" default answer "" buttons {{"Cancel", "OK"}} default button 2
return text returned of Input as string
end tell""".format(title=quote(title), question=quote(question)))
def main():
input = sys.stdin.read()
regex = dialog("RegEx", "Regular Expression e.g. /foo/bar/g")
if not regex:
sys.stdout.write(input)
sys.exit(0)
sep = regex[0]
try:
_, find_re, rep, opt = regex.split(sep)
except ValueError:
sys.stdout.write(input)
sys.exit(0)
flags = 0
count = 1
if "i" in opt:
flags |= re.I
elif "g" in opt:
count = 0
sys.stdout.write(re.sub(find_re, rep, input))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment