#!/usr/bin/perl
#
# tok -- extract tokens from input text
#
# Like grep(1) but prints only the matching part of a line.
#
# Options:
# -e <regex> -- regular expression to match
# -f <fmt> -- print matches using <fmt>
# -1 -- print one match per format
#
use Getopt::Std;
getopts('1e:f:');
$regexp = $opt_e || shift @ARGV;
my %ec = ('n' => "\n");
if ($opt_f) {
($format = $opt_f) =~
s/\\(.)/defined($ec{$1}) ? $ec{$1} : $1/ge;
}
while (<>) {
chomp;
next unless (@matches = m/$regexp/og);
if ($format) {
if ($opt_1) {
printf($format, $_) for @matches;
}
else {
printf($format, @matches);
}
}
else {
print join("\n", @matches, '');
}
}