如何从一个文件中读取一个字符串,并使用perl检查该字符串是否在另一个文件中

时间:2014-04-11 12:09:51

标签: perl

我有两个文本文件。一个文件包含一些数据,如

 hi 
 how

和另一个文件,如

L_ hello hi whats up
 N_ david
 N_ jhon
 N_ abraham
 N_ mc D  
L_ hey how u doing
 N_ david
 N_ jhon
 N_ abraham
 N_ mc D
L_ some blah blah blah
 N_ david
 N_ jhon
 N_ abraham
 N_ mc D

如何从第一个文件中取一行并检查另一个文件中是否存在此行?

如果该行存在(例如我的示例中为hi),我只需要打印该搜索字符串以及该行下方的名称。考虑L_是行的一些标识符,如果字符串存在于该行中,我们检查字符串我想在标识符N_的行下面打印名称,而不打印其他行的名称应删除标识L_N_

我正在寻找有关如何使用Perl解决此问题的建议。

3 个答案:

答案 0 :(得分:1)

perl -ne'
  BEGIN{
  $x = pop;
  ($re) = map qr/$_/, join "|", map /(\w+)/ && qr/\Q$1/, <>;
  @ARGV = $x;
  }
  $b = /($re)/ and print("\n$1"),next if /^L_/;
  chomp; s/^\w+_//;
  print if $b
' file1 file2

输出

hi david jhon abraham mc D
how david jhon abraham mc D

答案 1 :(得分:0)

试试这个:

#!/usr/bin/perl

use strict;
use warnings;

open my $patterns, '<', "$ARGV[0]"
    or die "Cannot open $ARGV[0]:$!";
open my $data, '<', "$ARGV[1]"
    or die "Cannot open $ARGV[1]:$!";

my @patterns;
while (<$patterns>) {
    chomp;
    push @patterns, $_;
}

my $line;
LINE: while ($line = <$data>) {
    chomp $line;
    if ($line =~ m/^\s*L_/) {
        foreach my $pat (@patterns) {
            if ($line =~ m/$pat/) {
                print "$line\n";
                while ($line = <$data>) {
                    if ($line =~ m/^\s*N_/) {
                        print $line;
                    }
                    else {
                        redo LINE;
                    }
                }
            }
        }
    }
}

答案 2 :(得分:0)

您可能希望查看perl函数open和grep。

    my $datafile = "some_data_file.txt";
    my $comparefile = "data_to_compare.txt";
    open ( my $data_filehandle, "<", $datafile ) or die $!;
    my @things_to_find = <$data_filehandle>;

    open ( my $compare_filehandle, "<", $comparefile ) or die $!;
    while ( my $line = <$compare_filehandle> ) 
    {
       foreach my $thing ( @things_to_find )
       {
          print "Match found with: $line" if $line =~ m/$thing/;
          print "Next line is :", <$compare_filehandle>;
       }
    }

&#39>拉出与图案匹配的线条,然后打印以下行。我将让您了解解析每一行的细节。 perlre上的perl文档将在这里为您提供帮助。