使用perl在文本文件中grep word

时间:2014-12-18 23:27:38

标签: perl command-line

我在myfolder中有一个文本文件A00010.txt A00011.txt A00012.txt到A00099.txt,其中包含不同的条目,如

umxwtdn8vtnt_n
umxwtdtnt_nn8v
umxwt_ntdn8vtn
u8vtnt_nmxwtdn
utnt_nmxwtdn8v

我的perl代码是

#!/usr/bin/perl
use strict;

        my $count = 10; 
        for ($count = 10; $count<= 99; $count++) { 
            my $result = `/bin/cat /myfolder/A000$count.txt  | grep "umxwtdn8vtnt_n"`;
            return $result;
        }

     print $result;

我试图获得$ result值但显示为空

2 个答案:

答案 0 :(得分:3)

/myfolder真的在根目录中吗? (你在ls /看到了什么?你看到myfolder吗?)在Unix系统的根目录中添加东西是非常罕见的,我认为你不会弄乱{{1} }}

此外,您在子例程(/)之外返回$result,如果是这种情况,则应该得到Perl运行时错误。

如果要复制代码片段,请注意sub { }是一个局部变量,它在子例程结束后消失。

答案 1 :(得分:2)

你真的需要使用Perl吗?

如果不是:

find /myfolder -name "A000??.txt" | xargs grep -n "umxwtdn8vtnt_n"

将在您的文件中找到该模式并告诉您哪一行......

您想知道该模式是否在您的一个或多个文件中吗?然后:

 my $not_found = 1;
 for (my $count = 10; $count<= 99; $count++) { 
    my $result = `grep "umxwtdn8vtnt_n" /myfolder/A000$count.txt`;
    if ($result) {
        print $result;
        $not_found = 0; # error level 0 = no error = found
        last;
    }
 }
 exit $not_found; # error level 1 = error = not found

仍在努力了解您的需求......如何:

my $result;
for (my $count = 10; $count<= 99; $count++) { 
   # you should test that A000$count.txt actually exists here
   my $match = `grep "umxwtdn8vtnt_n" /myfolder/A000$count.txt`;
   if ($match == "umxwtdn8vtnt_n") {
        print "found $match in A000${count}.txt";
        $result = $match;
        last; # exit for loop
    }
}
if ($result) {
    # do something with it?
}