def initialize
@line_nums=[]
@lines=[]
set_filaname
set_target
find
end
def set_filaname
puts "请输入目标文件名,包括绝对路径,在相同目录下可省略路径"
@filename=gets().chomp
end
def set_target
puts "请输入要查找的字符" @target=gets().chomp
end
#打印查找的结果
def result
puts "\n"+"*"*80
puts "目标文件为:"+@filename
puts "要查找的文本为:"+@target
if @line_nums[0]
puts "\n行号 文本"
for i in 0...@line_nums.length
puts @line_nums[i].to_s+" "*8+@lines[i]
end
else
puts "\n指定文件中没有要找的文本信息"
end
end
#查找,并记录行号和所在行文本
def find
file=open(@filename,"r")
line_num=0
file.each_line{|line|
line_num += 1
if line =~ /#{@target}/
@line_nums << line_num
@lines << line
end
}
end
end