计算文件中包含字符串的行数的优雅方法
我有一个简单的问题。
正如标题所说,我想找到一种方法来计算 PHP 文件中包含指定字符串的行数。
我知道我可以简单地打开文件并循环遍历所有行,看看是否有匹配的内容,但这似乎有点麻烦。有更好的办法吗?
为了进一步说明我想要做什么,下面是 awk 的样子:
awk '/KEYWORD/ {i++} END { print i }' FILE
谢谢!
I have a quick question.
As the title says, I'd like to find a way to count the number of lines that contain a specified string in a file, in PHP.
I know I could simply open the file and loop through all the lines and see if anything matches, but that seems kind of cumbersome. Is there a better way?
To further illustrate what I want to do, here's how it could look with awk:
awk '/KEYWORD/ {i++} END { print i }' FILE
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对我来说似乎并不“麻烦”:
您也许可以使用正则表达式,但如果您真的想计算行数(而不是实例),那么肯定没有更干净的方法(就简洁性和清晰度而言) )比上面的方法。
编辑,根据第一条评论:
那应该有效。
This hardly seems "cumbersome" to me:
You might be able to get away with a regular expression, but if you truly want to count the lines (as opposed to instances), there's surely not a cleaner way (in terms of brevity and clarity) than the above method.
Edit, per the first comment:
That should work.
请注意,当使用愚蠢的大文件(例如 500MB+)运行时,file() 会阻塞。如果这在您的 Web 应用程序中很常见,例如许多并发用户计算巨大的文件大小,这将影响性能。
be aware that file() will choke when run with stupid huge files such as 500MB+. If this is common in your web application, such as many concurrent users counting huge file sizes, this will impact on performance.