require 'optparse'
options = {
replace: false,
replace_with: ''
}
OptionParser.new do |opts|
opts.banner = "Usage: grep_like.rb [options] search_string file1 file2 ..."
opts.on('-i', '--replace REPLACE_WITH', 'Replace the matched string in the file') do |replace_with|
options[:replace] = true
options[:replace_with] = replace_with
end
end.parse!
search_string = ARGV.first
file_paths = ARGV[1..-1]
file_paths.each do |file_path|
if File.file?(file_path)
lines = File.readlines(file_path)
new_lines = []
lines.each do |line|
if line.include?(search_string)
if options[:replace]
new_lines << line.gsub(search_string, options[:replace_with])
else
puts line.chomp
end
else
new_lines << line
end
end
if options[:replace]
File.write(file_path, new_lines.join)
end
else
puts "Warning: #{file_path} is not a valid file."
end
end