3 ms·
I've been playing with writing a Python-based AWK-inspired library over the last couple weeks. This isn't an implementation of AWK like here, but a Python inte
by linsomniac 8y ago
I've been playing with writing a Python-based AWK-inspired library over the last couple weeks. This isn't an implementation of AWK like here, but a Python interpretation of "If I wanted to do the sort of things that AWK is good at, in Python, what would that look like?"
For example, to extract and add line numbers to SQL table definitions:
t = gawk.Gawk(sys.stdin)
t.context.data = ''
@t.range(r'CREATE TABLE', r');')
def line(context, line):
context.data += (('line %d:' % context.range.line_number) + line)
if context.range.is_last_line:
print(context.data)
context.data = ''
t.run()
https://github.com/linsomniac/gawk https://github.com/linsomniac/gawk
I've used AWK for close to 30 years, but I've never achieved or maintained any level of proficiency at it. I pretty much just use it for "{ print $1, $3 }" in a filter or the like. Every time I try to do something more complicated I spend an hour or more futzing around with it and more often than not getting to: almost but not quite" where I want to be. This is, of course, a me failing not an awk failing.
But it's left me wanting something that would make doing awk-like processes easy in Python, which I'm very proficient at.
I ended up using the name "gawk" because it's an English word and nods to the AWK inspiration, but then I remembered GnuAWK so I'll probably rename it.
- srean 8y agoYeah Gawk is Gnu's Awk, its a well established name. Your code snippet does showcase Awk's utility. It brutally cuts through all the ceremony around reading and iterating over lines.