Skip to content

Commit

Permalink
Initial working sed. I mean, yeah, working.
Browse files Browse the repository at this point in the history
  • Loading branch information
Zed A. Shaw committed Dec 15, 2017
1 parent 95dcd55 commit 3ff998e
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 8 deletions.
11 changes: 9 additions & 2 deletions ex49_sed/ed/ed.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
import re
import ed
from ed.scanner import Scanner
from ed.parser import EdParser
Expand Down Expand Up @@ -62,10 +63,16 @@ def quit(self):
sys.exit(0)

def read(self, file_name, address=None):
self.lines += open(file_name).readlines()
self.lines += [x.rstrip() for x in open(file_name).readlines()]

def subst(self, pattern, replace, start=None, end=None):
pass
repat = re.compile(pattern)
new_lines = []

for line in self.lines:
new_lines.append(repat.sub(replace, line))

self.lines = new_lines

def write(self, file_name=None):
file_name = file_name or self.file_name
Expand Down
8 changes: 8 additions & 0 deletions ex49_sed/ed/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ def root(self):
self.write()
elif start == 'QUIT':
self.buffer.quit()
elif start == 'SUBST':
self.subst()
elif start == 'INTEGER':
# this is an address
self.address()
Expand Down Expand Up @@ -115,3 +117,9 @@ def join(self):
self.match('JOIN')
self.buffer.join(*self.calc_range())

def subst(self):
self.match('SUBST')
pat_tok = self.match('PATTERN')[1]
_, pattern, replace, _ = pat_tok.split('/')
self.buffer.subst(pattern, replace)

2 changes: 2 additions & 0 deletions ex49_sed/ed/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ class Scanner(object):
L(r'^w', 'WRITE'),
L(r'^j', 'JOIN'),
L(r'^q', 'QUIT'),
L(r'^s', 'SUBST'),
L(r"^[0-9]+", "INTEGER"),
L(r"^\+", "PLUS"),
L(r"^\-", "MINUS"),
L(r"^\s+", "SPACE"),
L(r"^,", "COMMA"),
L(r'/.*/.*/', 'PATTERN'), # won't work totally
L(r'^.*', "FILE_NAME"), # terrible regex
]

Expand Down
22 changes: 16 additions & 6 deletions ex49_sed/run.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import readline
import sys
import argparse
from ed import ed

parser = argparse.ArgumentParser()
parser.add_argument("infile", type=str, help="Input file.")
parser.add_argument("-e", type=str, help="The script.")
parser.add_argument("-f", type=str, help="A file script.", default=None)
parser.add_argument("-n", action="store_true")
args = parser.parse_args()

buffer = ed.Buffer()
buffer.edit(args.infile)

while True:
try:
line = input("> ")
if args.e:
ed.process(args.e, buffer)
elif args.f:
lines = (x.strip() for x in open(args.f).readlines())
for line in lines:
ed.process(line, buffer)
except EOFError:
print()
sys.exit(0)

print("\n".join(buffer.lines))

0 comments on commit 3ff998e

Please sign in to comment.