如何在 Perl 中搜索多个文件以查找字符串? [英] How can I search multiple files for a string in Perl?

查看:90
本文介绍了如何在 Perl 中搜索多个文件以查找字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题可能很简单,但我是一个完整的新手.我想在多个文本文件的内容中搜索特定短语,然后在屏幕上显示找到的行.我已经学会了如何处理单个文件.比如我要搜索一个词,在F的根目录下一个名为wyvern.txt"的文本文件中说好的",代码如下:

My question is probably simple but I'm a complete newbie. I want to search the contents of multiple text files for a particular phrase and then display the lines of the finds on screen. I've already learnt how to deal with a single file. For example, if I want to search for a word, say "Okay" in a text file named "wyvern.txt" in the root directory of F. The following code works:

#!/usr/bin/perl

$file = 'F:\wyvern.txt';
open(txt, $file);
while($line = <txt>) {
  print "$line" if $line =~ /Okay/;
}
close(txt);

但是如果我想在两个文本文件中搜索同一个短语,分别说wyvern"和casanova"怎么办?或者F的根目录下novels"目录下的所有文件怎么办?.

But what should I do if I want to search for the same phrase in two text files, say "wyvern' and "casanova" respectively? or how about all the files in the directory "novels" in the root directory of F.

任何帮助将不胜感激.提前致谢

Any help would be greatly appreciated. Thanks in advance

迈克

哈哈,我终于知道如何搜索目录中的所有文件以进行模式匹配了:)以下代码效果很好:

Haha, I finally figured out how to search all the files in a directory for a pattern match:) The following code works great:

#!/usr/bin/perl  
@files = <F:/novels/*>;
foreach $file (@files) {
open   (FILE, "$file");
while($line= <FILE> ){
print "$line" if $line =~ /Okay/;
}
close FILE; 
} 

推荐答案

扩展 Jonathan Leffler 提供的好答案:

Extending the good answer provided by Jonathan Leffler:

找到匹配的文件名在$ARGV中,稍作改动,行号可以在$.中找到.示例:

The filename where the match was found is in $ARGV, and with a small change, the line number can be found in $.. Example:

while (<>) {
  print "$ARGV:$.:$_" if /pattern/;
} continue {
  close ARGV if eof; # Reset $. at the end of each file.
}

此外,如果您有一个文件名列表并且它们不在命令行中,您仍然可以获得神奇的 ARGV 行为.观看:

Furthermore, if you have a list of filenames and they're not on the commandline, you can still get the magic ARGV behavior. Watch:

{
  local @ARGV = ('one.txt', 'two.txt');
  while (<>) {
    print "$ARGV:$.:$_" if /Okay/;
  } continue {
    close ARGV if eof;
  }
}

这是对一系列文件进行逐行处理的普遍有用的模式,无论它是什么——即使我可能会推荐 File::GrepApp::Ack 对于这个特定问题:)

Which is a generally useful pattern for doing line-by-line processing on a series of files, whatever it is -- even if I might recommend File::Grep or App::Ack for this specific problem :)

这篇关于如何在 Perl 中搜索多个文件以查找字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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