Skip to content

Instantly share code, notes, and snippets.

@nipuntalukdar
Created July 4, 2018 07:07
Show Gist options
  • Select an option

  • Save nipuntalukdar/888544a8f214c9cf3336a9c38f046fb1 to your computer and use it in GitHub Desktop.

Select an option

Save nipuntalukdar/888544a8f214c9cf3336a9c38f046fb1 to your computer and use it in GitHub Desktop.
Script to replace multiple mattching lines with another set of lines
from __future__ import print_function
import sys
import re
if len(sys.argv) < 3:
print('{} <input-file> <line-seq-file><replace-lines-file>'.format(sys.argv[0]))
sys.exit(1)
input_lines = []
line_seq = []
replace_lines = []
try:
with open(sys.argv[1]) as fp:
input_lines = fp.readlines()
if not input_lines:
print('No input lines given')
sys.exit(1)
with open(sys.argv[2]) as fp:
line_seq = fp.readlines()
if not line_seq:
print('No lines seq given')
sys.exit(1)
with open(sys.argv[3]) as fp:
replace_lines = fp.readlines()
if not replace_lines:
print('No replace lines given lines given')
sys.exit(1)
mod_line_seq = [re.sub(r"\s+", "", x) for x in line_seq]
found = 0
max_found = len(mod_line_seq)
idx = 0
while idx < len(input_lines):
mod_i = re.sub(r"\s+", "", input_lines[idx])
if mod_i == mod_line_seq[found]:
found += 1
else:
for a in range(idx - found, idx + 1):
print (input_lines[a], end='')
found = 0
if found == max_found:
for a in replace_lines:
print(a, end='')
found = 0
idx += 1
except Exception as e:
print(e)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment