#!/usr/bin/env ruby # stem [-0] PAT SUBST... -- ... - substitute make(1)-style percent patterns # # Pattern groups are split by --. For the first pattern group where # PAT matches, substitute the first % in all SUBST and print them. # Patterns without / match the basename. if ARGV[0] == "-0" ARGV.shift $\ = $/ = "\0" else $\ = $/ = "\n" end stems = ARGV.inject([[]]) { |a, e| if e == "--" a << [] else a.last << e end a } while line = STDIN.gets line.chomp! stems.each { |base, *gens| if base.index("/") dir = "" else dir, line = File.split(line) if dir == "." dir = "" else dir << "/" end end if i = base.index("%") if line.size >= base.size && line.start_with?(base[0...i]) && line.end_with?(base[i+1..-1]) gens.each { |gen| if j = gen.index("%") print "#{gen[0...j]}#{dir}#{line[i..-base.size+i]}#{gen[j+1..-1]}" else print "#{dir}#{gen}" end } break end else if line == base gens.each { |gen| print "#{dir}#{gen.sub('%', line)}" } end end } end