2
# -*- coding: utf-8 -*-
4
# Copyright 2014-2015 Canonical Limited.
6
# This file is part of charm-helpers.
8
# charm-helpers is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU Lesser General Public License version 3 as
10
# published by the Free Software Foundation.
12
# charm-helpers is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
20
__author__ = 'Jorge Niedbalski <niedbalski@ubuntu.com>'
26
def sed(filename, before, after, flags='g'):
28
Search and replaces the given pattern on filename.
30
:param filename: relative or absolute file path.
31
:param before: expression to be replaced (see 'man sed')
32
:param after: expression to replace with (see 'man sed')
33
:param flags: sed-compatible regex flags in example, to make
34
the search and replace case insensitive, specify ``flags="i"``.
35
The ``g`` flag is always specified regardless, so you do not
36
need to remember to include it when overriding this parameter.
37
:returns: If the sed command exit code was zero then return,
38
otherwise raise CalledProcessError.
40
expression = r's/{0}/{1}/{2}'.format(before,
43
return subprocess.check_call(["sed", "-i", "-r", "-e",
45
os.path.expanduser(filename)])