Last active
August 29, 2015 14:08
-
-
Save vroy/8dae1d39544fad407924 to your computer and use it in GitHub Desktop.
A simple utility to extract patterns out of input streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# A simple utility to extract patterns out of input streams | |
# | |
# Heavily inspired by: | |
# http://jstorimer.com/2011/12/12/writing-ruby-scripts-that-respect-pipelines.html | |
# https://gist.github.com/jstorimer/1465437 | |
# | |
# Examples: | |
# | |
# $ extract PATTERN Gemfile | |
# $ extract PATTERN Gemfile | more | |
# $ extract PATTERN Gemfile > output.txt | |
# $ extract PATTERN Gemfile Gemfile.lock | |
# $ cat Gemfile* | extract PATTERN | |
# | |
# Install: | |
# $ curl https://gist.githubusercontent.com/exploid/8dae1d39544fad407924/raw/2d0da9234de179c43d5e3020e6b6272f10ed3d80/extract.rb > ~/bin/extract | |
# $ chmod +x ~/bin/extract | |
require 'optparse' | |
$options = { } | |
OptionParser.new do |opts| | |
opts.banner = "A simple utility to extract patterns out of input streams" | |
opts.separator "" | |
opts.separator "Usage:" | |
opts.separator " extract PATTERN Gemfile" | |
opts.separator " extract PATTERN Gemfile | more" | |
opts.separator " extract PATTERN Gemfile > output.txt" | |
opts.separator " extract PATTERN Gemfile Gemfile.lock" | |
opts.separator " cat Gemfile* | extract PATTERN" | |
opts.separator "" | |
opts.separator "Specific options:" | |
opts.on("-i", "--ip", "Match IP addresses") do |ip| | |
$options[:extract_pattern] = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ | |
end | |
opts.on("-p", "--pattern", String, "PATTERN (Ruby regular expression)") do |pattern| | |
$options[:extract_pattern] = pattern | |
end | |
opts.on("-h", "--help", "help") do |h| | |
puts opts | |
exit | |
end | |
end.parse! | |
if $options[:extract_pattern].nil? | |
$options[:extract_pattern] = ARGV.shift || "" | |
end | |
# Keep reading lines of input as long as they're coming. | |
while input = ARGF.gets | |
input.each_line do |line| | |
if $options[:extract_pattern] | |
matches = line.scan(Regexp.new($options[:extract_pattern])) | |
if matches.any? | |
begin | |
$stdout.puts matches.join(", ") | |
rescue Errno::EPIPE | |
exit(74) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment