在文件中搜索字符串的最佳方法是什么? [英] What's the best way to search for a string in a file?

查看:42
本文介绍了在文件中搜索字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题不言自明.我只想知道它是否存在,而不是它在哪里.有没有一种班轮可以实现这一目标?

The title speaks for itself really. I only want to know if it exists, not where it is. Is there a one liner to achieve this?

推荐答案

File.open(filename).grep(/string/)

这会将整个文件加载到内存中(吞咽文件).你应该避免文件 slurping 处理大文件时.这意味着一次加载一行,而不是整个文件.

This loads the whole file into memory (slurps the file). You should avoid file slurping when dealing with large files. That means loading one line at a time, instead of the whole file.

File.foreach(filename).grep(/string/)

最好自己清理,而不是让垃圾收集器在某个时候处理它.如果您的程序是长期存在的,而不仅仅是一些快速脚本,则这一点更为重要.使用代码块可确保 File 对象在代码块终止时关闭.

It's good practice to clean up after yourself rather than letting the garbage collector handle it at some point. This is more important if your program is long-lived and not just some quick script. Using a code block ensures that the File object is closed when the block terminates.

File.foreach(filename) do |file|
  file.grep(/string/)
end

这篇关于在文件中搜索字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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