字串在多個檔案中出現

字串在多個檔案中出現

我有兩個文件

  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

應該這樣做。

在 中perl,您還需要打開keyword.txt並循環遍歷每個關鍵字,依次 grep ,就像您在程式碼中單獨對 1 所做的那樣。

答案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

相關內容