Ruby Regular Expression Tool

Posted by Tully on Tue 17 December 2013

I wanted a simple Regular expression tool that I could pipe data to and return specific capture groups based on my regular expression.

The reason I coded this was that GREP and EGREP did not have the functionality to bring back specific sets of data based on your REGEX. There are other tools that are able to do this, but this is simple to write and does what I needed.

The below code will take a regular expression and optional capture groups (1,2,etc) that you want returned.

Ruby Regular Expression Tool

#!/usr/bin/env ruby
#
# This script takes data from STDIN and runs it through the regular expression
# defined in the first parameter. Any params after the regex are optional and
# will be used to define the sections to print.
#
# The below example will parse ps output and display the Date, Time, and Command.
#
# ps aux | ./regex '([a-zA-Z]+\d+)\s+([0-9]+:[0-9]+)\s+(.*)' 1 2 3

unless ARGV.length >= 1
    puts <<USAGE
    Usage: DATA | ./regex REGEX [CAPTURED_GROUPS]
    USAGE
    exit 1
end

line = STDIN.gets
pattern = /#{ARGV[0]}/
ARGV.shift

while line
    if pattern =~ line
        if ARGV.length > 0
            ARGV.each do |num|
                part = "$#{num}"
                print "#{eval part} "
            end
            puts
        else
            puts line
        end
    end
    line = STDIN.gets
end
    Usage: DATA | ./regex REGEX [CAPTURED_GROUPS]
    USAGE
    exit 1
end

line = STDIN.gets
pattern = /#{ARGV[0]}/
ARGV.shift

while line
    if pattern =~ line
        if ARGV.length > 0
            ARGV.each do |num|
                part = "$#{num}"
                print "#{eval part} "
            end
            puts
        else
            puts line
        end
    end
    line = STDIN.gets
end