
ファイルが2つあります。
- 入力.txt
- キーワード.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に対して個別に行ったように、各キーワードを開いて繰り返しながら順番にgrepingするperl
必要があります。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