Ruby 在文件中查找字符串并打印结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10832440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:28:37  来源:igfitidea点击:

Ruby find string in file and print result

ruby-on-railsruby

提问by Matheus Moreira

It's been a very long time since I've used ruby for things like this but, I forget how to open a file, look for a string, and print what ruby finds. Here is what I have:

我已经很长时间没有使用 ruby​​ 做这样的事情了,但是,我忘记了如何打开文件、查找字符串以及打印 ruby​​ 找到的内容。这是我所拥有的:

#!/usr/bin/env ruby
f = File.new("file.txt")
text = f.read
if text =~ /string/ then
puts test
end

I want to determine what the "document root" (routes) is in config/routes.rb

我想确定 config/routes.rb 中的“文档根”(路由)是什么

If I print the string, it prints the file.

如果我打印字符串,它会打印文件。

I feel dumb that I don't remember what this is, but I need to know.

我觉得很愚蠢,我不记得这是什么,但我需要知道。

Hopefully, I can make it print this:

希望我可以让它打印这个:

# Route is:
blah blah blah blah

回答by Matheus Moreira

File.open 'file.txt' do |file|
  file.find { |line| line =~ /regexp/ }
end

That will return the first line that matches the regular expression. If you want allmatching lines, change findto find_all.

这将返回与正则表达式匹配的第一行。如果您想要所有匹配的行,请更改findfind_all.

It's also more efficient. It iterates over the lines one at a time, without loading the entire file into memory.

它也更有效率。它一次遍历一行,而不将整个文件加载到内存中。

Also, the grepmethod can be used:

此外,该grep方法可以用于:

File.foreach('file.txt').grep /regexp/

回答by iain

The simplest way to get the root is to do:

获得根的最简单方法是:

rake routes | grep root

If you want to do it in Ruby, I would go with:

如果你想在 Ruby 中做到这一点,我会选择:

File.open("config/routes.rb") do |f|
  f.each_line do |line|
    if line =~ /root/
      puts "Found root: #{line}"
    end
  end
end

回答by gmaliar

Inside textyou have the whole file as a string, you can either match against it using a .matchwith regexp or as Dave Newton suggested you can just iterate over each line and check. Something such as:

在内部,text您将整个文件作为一个字符串,您可以使用.matchwith regexp匹配它,或者按照 Dave Newton 的建议,您可以遍历每一行并进行检查。例如:

f.each_line { |line|
  if line =~ /string/ then
    puts line
  end
}