Ruby在文件和打印结果中查找字符串
自从我将ruby用于这样的事情以来,已经很长时间了,但是,我忘记了如何打开文件,查找字符串以及打印ruby发现的内容。 这是我有的:
#!/usr/bin/env ruby f = File.new("file.txt") text = f.read if text =~ /string/ then puts test end
我想确定config / routes.rb中的“文档根”(路由)是什么
如果我打印字符串,它会打印文件。
我感到愚蠢,我不记得这是什么,但我需要知道。
希望我可以打印出来:
# Route is: blah blah blah blah
File.open 'file.txt' do |file| file.find { |line| line =~ /regexp/ } end
这将返回与正则表达式匹配的第一行。 如果您想要所有匹配的行, find_all
更改为find_all
。
它也更有效率。 它一次迭代一行,而不将整个文件加载到内存中。
此外,可以使用grep
方法:
File.foreach('file.txt').grep /regexp/
获取root的最简单方法是:
rake routes | grep root
如果你想在Ruby中做,我会选择:
File.open("config/routes.rb") do |f| f.each_line do |line| if line =~ /root/ puts "Found root: #{line}" end end end
在text
内部,您将整个文件作为字符串,您可以使用带有regexp的.match
进行匹配,或者像Dave Newton建议您可以遍历每一行并检查。 像这样的东西:
f.each_line { |line| if line =~ /string/ then puts line end }