Skip to content

Instantly share code, notes, and snippets.

@markevans
Created June 6, 2018 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markevans/77cbdc78a3349b8b6cd3dfbea29b49a3 to your computer and use it in GitHub Desktop.
Save markevans/77cbdc78a3349b8b6cd3dfbea29b49a3 to your computer and use it in GitHub Desktop.
command line tool for inline-editing (edit_inline PATTERN(regexp) REPACEMENT(ruby code outputting string) FILE(path to file))
#!/usr/bin/env ruby
require 'open3'
require 'optparse'
script_name = File.basename($0)
options = {}
option_parser = OptionParser.new do |opts|
opts.banner = <<-HEREDOC
Usage:
#{script_name} PATTERN REPLACEMENT FILE
Example:
#{script_name} 'name="(.*?)"' '"name: \#{$1.to_i}"' code.rb
HEREDOC
opts.on("-w", "--write", "Write to file") do
options[:write] = true
end
opts.on("-d", "--diff", "Show diff") do
options[:diff] = true
end
opts.on("-h", "--help", "Show help") do |o|
puts option_parser
exit
end
end
option_parser.parse!
if ARGV.length == 3
pattern, replacement, file = ARGV
else
puts option_parser
exit
end
matcher = Regexp.new(pattern, Regexp::MULTILINE)
body = File.read(file)
new_body = body.gsub(matcher){|| eval(replacement) }
if options[:diff]
Open3.pipeline_w("diff #{file} -") {|i| i.puts new_body }
elsif options[:write]
File.write(file, new_body)
else
puts new_body
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment