Ruby 在文件中查找字符串并打印结果 [英] Ruby find string in file and print result

查看:57
本文介绍了Ruby 在文件中查找字符串并打印结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

I want to determine what the "document root" (routes) is in 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

推荐答案

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

这将返回与正则表达式匹配的第一行.如果您想要所有匹配的行,请更改<代码>查找find_all.

That will return the first line that matches the regular expression. If you want all matching lines, change find to find_all.

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

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

此外,grep方法:

Also, the grep method can be used:

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

这篇关于Ruby 在文件中查找字符串并打印结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆