-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprefix_lines.py
24 lines (22 loc) · 1.01 KB
/
prefix_lines.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import io
import argparse
import re
argparser = argparse.ArgumentParser()
argparser.add_argument("-i", "--input_filename", required=True)
argparser.add_argument("-o", "--output_filename", required=True)
argparser.add_argument("-p", "--prefix", type=str, required=True,
help="the string to prefix lines.")
argparser.add_argument("-r", "--regex", type=str, default='.+\\n',
help="only apply the prefix to lines which match this regular expression")
argparser.add_argument("-remove-prefix", action='store_true', help='Instead of inserting the prefix, remove it (when it exists)')
args = argparser.parse_args()
prefix = args.prefix
regex = re.compile(args.regex)
with open(args.input_filename) as input_file, open(args.output_filename, mode='w') as output_file:
for line in input_file:
if regex.search(line):
if args.remove_prefix:
line = line[len(prefix):] if line.startswith(prefix) else line
else:
line = prefix + line
output_file.write(line)