Created
February 26, 2016 13:31
-
-
Save abargnesi/9b04338d9f7e36cc165b to your computer and use it in GitHub Desktop.
Replace matched lines with a replacement line over a file.
This file contains 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
#!/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