Skip to content

Instantly share code, notes, and snippets.

@Drvanon
Created March 13, 2019 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drvanon/27ac93a092c8c72cddbc2754cc19d1ae to your computer and use it in GitHub Desktop.
Save Drvanon/27ac93a092c8c72cddbc2754cc19d1ae to your computer and use it in GitHub Desktop.
Simple script to act as a sed with python regex
#! /usr/bin/env python
# credit for the function to https://stackoverflow.com/a/40843600
# Commandline-ification by Robin A. Dorstijn
import re
import shutil
from tempfile import mkstemp
import click
@click.command()
@click.argument("pattern")
@click.argument("replace")
@click.argument("source", type=click.Path(exists=True))
@click.option("--dest", type=click.Path(exists=True))
@click.option("--count", type=click.INT, default=0)
def sed(pattern, replace, source, dest=None, count=0):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
Args:
pattern (str): pattern to match (can be re.pattern)
replace (str): replacement str
source (str): input filename
count (int): number of occurrences to replace
dest (str): destination filename, if not given, source will be over written.
"""
fin = open(source, 'r')
num_replaced = count
if dest:
fout = open(dest, 'w')
else:
fd, name = mkstemp()
fout = open(name, 'w')
for line in fin:
out = re.sub(pattern, replace, line)
fout.write(out)
if out != line:
num_replaced += 1
if count and num_replaced > count:
break
try:
fout.writelines(fin.readlines())
except Exception as E:
raise E
fin.close()
fout.close()
if not dest:
shutil.move(name, source)
if __name__=="__main__":
sed()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment