import re
import tempfile
import shutil


def replace_inplace(file_name, search, replace):
    """ Do a simple in-place regex search/replace. """
    reg = re.compile(search)
    tot_n_subs = 0
    with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp_file:
        with open(file_name, "r") as cfile:
            for line in cfile:
                line, n_subs = reg.subn(replace, line)
                tot_n_subs += n_subs
                tmp_file.write(line)
        tname = tmp_file.name
    shutil.move(tname, file_name)
    return tot_n_subs