Ruby在文件和打印結果中查找字符串

[英]Ruby find string in file and print result


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

3 个解决方案

#1


8  

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 all matching lines, change find to find_all.

這將返回與正則表達式匹配的第一行。如果您想要所有匹配的行,請將find更改為find_all。

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

它也更有效率。它一次迭代一行,而不將整個文件加載到內存中。

Also, the grep method can be used:

此外,可以使用grep方法:

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

#2


2  

The simplest way to get the root is to do:

獲取root的最簡單方法是:

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

#3


1  

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

在文本內部,您將整個文件作為字符串,您可以使用帶有regexp的.match進行匹配,或者像Dave Newton建議您可以遍歷每一行並檢查。像這樣的東西:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/05/31/72602061304a41e624e3adada313428f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com