Skip to content

Instantly share code, notes, and snippets.

@abargnesi
Created February 26, 2016 13:31
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 abargnesi/9b04338d9f7e36cc165b to your computer and use it in GitHub Desktop.
Save abargnesi/9b04338d9f7e36cc165b to your computer and use it in GitHub Desktop.
Replace matched lines with a replacement line over a file.
#!/usr/bin/env python2
# read program arguments
import sys
program_arguments = sys.argv[1:]
if len(program_arguments) != 3:
sys.stderr.write(
"usage: replace_line.py [FILE] [MATCH] [REPLACE]\n"
)
file_name, match_line, replace_line = program_arguments
# read lines from FILE, strip of new lines
with open(file_name, 'r') as f:
lines = map(lambda l: l.strip(), f.readlines())
def map_line(line):
'''
Returns [REPLACE] if line matches [MATCH], otherwise return
itself.
'''
if line == match_line:
return replace_line
else:
return line
# write replaced lines to FILE
with open(file_name, 'w') as f:
for line in map(map_line, lines):
f.write(line + "\n")
# vim: ft=python ts=4 sts=4 sw=4 expandtab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment