Heres a ruby script that comments lines by regular expression or line numbers.
Code:
#!/usr/bin/env ruby
def usage
puts <<EOS
Usage: #{__FILE__} [options] infile pattern1 [pattern2 ...]
-r --regexp comment all lines matchinp patterns (default)
-n --numbers comment by line numbers instead of patterns
-c --comment-mark <MARK> use <MARK> to comment (default=`#')
-f --file input file (default is first arg)
-h --help this help
EOS
end
$comment_mark = "#"
$by_number = false
$by_regexp = true
$input_file = nil
while ARGV.any?
case arg = ARGV.shift
when "-r", "--regexp"
$by_number = false
$by_regexp = true
when "-n", "--numbers"
$by_number = true
$by_regexp = false
when "-c", "--comment-mark", "--mark"
$comment_mark = ARGV.shift
when "-f", "--file"
$input_file = ARGV.shift
when "-h", "--help"
usage
exit 0
else
if $input_file
ARGV.unshift arg
else
$input_file = arg
end
break
end
end
unless $input_file
STDERR.write "no input file given\n"
exit 1
end
line_num = 0
File.open($input_file, 'r').each_line do |line|
line_num += 1
ARGV.each do |pattern|
if $by_number
number = pattern.to_i
if number == 0
STDERR.write "invalid line number: `#{pattern}'\n"
exit 1
end
if line_num == number
line = $comment_mark + line
end
elsif $by_regexp
if Regexp.new(pattern) =~ line
line = $comment_mark + line
end
end
end
puts line
end
Bookmarks