複数のファイル内の文字列の出現

複数のファイル内の文字列の出現

ファイルが2つあります

  1. 入力.txt
  2. キーワード.txt

input.txt次のような内容です:

.src_ref 0 "call.s" 24 first
      0x000000    0x5a80 0x0060         BRA.l 0x60
.src_ref 0 "call.s" 30 first
      0x000002    0x1bc5                RETI
.src_ref 0 "call.s" 31 first
      0x000003    0x6840                MOV R0L,R0L
.src_ref 0 "call.s" 35 first
      0x000004    0x1bc5                RETI

keyword.txt次のような内容です:

MOV
BRA.l
RETI
ADD
SUB
..
etc

ここで、このkeyword.txtファイルを読み取ってinput.txtファイル内を検索し、MOV何回発生したかを調べたいと思いますBRA.l

これまでのところ、私は単一のファイルからそれを動作させることに成功しました。これがコードです

#!/usr/bin/perl
use strict;
use warnings;

sub retriver();

my @lines;
my $lines_ref;
my $count;
$lines_ref=retriver();
@lines=@$lines_ref;
$count=@lines;
print "Count :$count\nLines\n";
print join "\n",@lines;

sub retriver()
{
    my $file='C:\Users\vk41286\Desktop\input.txt';
    open FILE, $file or die "FILE $file NOT FOUND - $!\n";
    my @contents=<FILE>;

    my @filtered=grep(/MOV R0L,R0L/,@contents);
    return \@filtered;
}

ここでは検索のみ可能でMOV、 のような他の指示を検索することはできませんRETI

MOV,RETIまた、などをファイルに入れてkeyword.txt汎用化したいと考えています。

出力は次のようになります。

MOV has occured 2  times
RETI has occured 1 time

答え1

困っていない場合はperl、シンプルなコマンドライン

 grep -f keyword.txt -c input.txt

それをすべきです。

では、コード内の 1 だけに対して行ったのと同じように、各キーワードをperl開いてループし、順番に grep を実行する必要があります。keyword.txt

答え2

bash-script はperl:よりもはるかに単純なようです。

while read keyword
do
    occurrence =$(grep -c -F "$keyword" input.txt)
    echo "$keyword has occurred $occurrence time(s)"
done < keyword.txt

関連情報