-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregex.py
executable file
·43 lines (36 loc) · 1.42 KB
/
regex.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/python
import re
import sys
import argparse
parser = argparse.ArgumentParser(description='Search with Python regular expressions')
parser.add_argument('-I', '--insensitive', action='store_true', help="Case insensitive search")
parser.add_argument('-n', '--noisy', action='store_true', help="Print only matching input")
parser.add_argument('-f', '--file', default=sys.stdin, type=argparse.FileType('r'), help="Input file")
parser.add_argument('-o', '--output', default=sys.stdout, type=argparse.FileType('w'), help="Output file")
parser.add_argument('needle',help="Regex to find")
parser.add_argument('replace',nargs='?',default="",help="(Optional) replacement regex, supports \\1 notation")
args = parser.parse_args()
sys.stderr.write("Needle: /%s/\n" % args.needle)
sys.stderr.write("Replace: /%s/\n" % args.replace)
sys.stderr.write("Insensitive: /%s/\n" % args.insensitive)
sys.stderr.write("Noisy: /%s/\n" % args.noisy)
if args.insensitive:
rneedle = re.compile(args.needle,re.IGNORECASE)
else:
rneedle = re.compile(args.needle)
instream = args.file
outstream = args.output;
sys.stderr.write("Replace: |%s|" % args.replace)
if args.replace:
# REPLACERS
for line in instream.readlines():
if rneedle.search(line):
outstream.write("%s" % rneedle.sub(args.replace,line))
else:
if args.noisy:
outstream.write(line)
else:
# FINDERS
for line in instream.readlines():
if rneedle.search(line):
outstream.write(line)