Created
May 31, 2012 15:05
-
-
Save mzupan/2844007 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def local_sed(filename, before, after, limit='', use_sudo=False, backup=''): | |
""" | |
Run a search-and-replace on ``filename`` with given regex patterns. | |
Equivalent to ``sed -i<backup> -r -e "/<limit>/ s/<before>/<after>/g | |
<filename>"``. | |
For convenience, ``before`` and ``after`` will automatically escape forward | |
slashes, single quotes and parentheses for you, so you don't need to | |
specify e.g. ``http:\/\/foo\.com``, instead just using ``http://foo\.com`` | |
is fine. | |
To maintain compatibility with Fabric's own sed, use_sudo is included by unused. | |
""" | |
func = local | |
for char in "\&": | |
after = after.replace(char, r'\%s' % char) | |
# Characters to be escaped in both | |
for char in "/'": | |
before = before.replace(char, r'\%s' % char) | |
after = after.replace(char, r'\%s' % char) | |
# Characters to be escaped in replacement only (they're useful in regexen | |
# in the 'before' part) | |
for char in "()": | |
after = after.replace(char, r'\%s' % char) | |
if limit: | |
limit = r'/%s/ ' % limit | |
# Test the OS because of differences between sed versions | |
with hide('running', 'stdout'): | |
platform = local("uname", capture=True) | |
if platform in ('Darwin'): | |
expr = r"sed -i '%s' -e '%ss/%s/%s/g' %s" | |
else: | |
expr = r"sed -i%s -r -e '%ss/%s/%s/g' %s" | |
command = expr % (backup, limit, before, after, filename) | |
return func(command) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment