Note that this basic framework does not support awk’s /regex1/,/regex2/
notation that captures lines between (and including) the lines matching
those regular expressions.
Best regards,
baptiste
–Greg
how about something like this simple implementation
AWK in Ruby
module AWK
class ClassAwk
def initialize(filename = “”)
@NR = 0; # record number
@NF = 0; # field number
@FS = /\s+/; # field separator
@line = “”; # line matched
@fields = []; # fields of macthed line
@trace = []; # regexp trace
if (filename == "")
@file = ARGF;
else
@file = File.open(filename, "r").close;;
end
end
#NOTE: every rule has to be in separate line
#to get unique rule id
def rule(regexp1, regexp2 = nil)
msg = "regexp parameter must be Regexp";
raise ArgumentError, msg unless regexp1.kind_of?(Regexp);
if regexp2 == nil
if @line =~ regexp1
@fields = @line.split(@FS)
yield
end
else
raise ArgumentError, msg unless regexp2.kind_of?(Regexp);
rule_id = /.+:([0-9]+)/.match(caller.first.to_s)[1].to_i;
@trace[rule_id] = true if @line =~ regexp1;
if @trace[rule_id]
@fields = @line.split(@FS)
yield
end
@trace[rule_id] = false if @line =~ regexp2;
end
end
def analyze()
@NR = 0;
ARGF.each { |@line|
@line = @line.chop;
@NR += 1;
yield
}
end
#get paricular field
def getField(index)
output = "";
if (index == 0)
output = @line;
else
if index - 1 < @fields.length
return @fields[index - 1];
end
end
end
#get NR (record number)
def getNR
return @NR;
end
#get number of fileds
def getNF
return @fields.length;
end
end
end
and an example how to use it:
require “awk.rb”
awk = AWK::ClassAwk.new();
awk.analyze() {
awk.rule(/start1/, /stop1/) {
print “1, NR:”, awk.getNR(),", ";
print "NF: “, awk.getNF(),”, “, awk.getField(0), “\n”;
};
awk.rule(/start2/, /stop2/) {
print “2, NR:”, awk.getNR(),”, ";
print "NF: “, awk.getNF(),”, ", awk.getField(0), “\n”;
};
awk.rule(/start1/) {
print awk.getField(0);
};
}