技術メモ

神奈川在住のITエンジニアの備忘録。おもにプログラミングやネットワーク技術について、学んだことを自分の中で整理するためにゆるゆると書いています。ちゃんと検証できていない部分もあるのでご参考程度となりますが、誰かのお役に立てれば幸いです。

複数のファイルから複数の項目を grep するスクリプト

一度に grep したくなったので、主題のスクリプトを作成した。
こういうのは、やっぱり perl で書くと楽。

use strict;

my $targets = [
	# ファイル名、key1, key2, key3, ...
	["fileA.txt", 
		"test.keyA1", "test.keyA2"],
	["fileB.txt", 
		"test.keyB1", "test.keyB2", "test.keyB3"],
	["fileC.txt", 
		"test.keyC1", "test.keyC2"]
];

foreach my $target (@$targets){
	grepFor($target);
}

sub grepFor {
	my $targetRef = shift;
	my @target = @$targetRef;
	my $file = $target[0];
	print "---------- $file ----------\n";
	open my $in, '<', $file or die "Can not open $file : $!";
	my @fileData = <$in>;
	close ($in);
	for (my $i = 1; $i <= $#target; $i++){
		# 正規表現を使わない grep の場合
		my $targetStr = quotemeta($target[$i]);
		my @matched = grep {/$targetStr/} @fileData;
		# 正規表現を使う grep の場合
		# my @matched = grep {/$target[$i]/} @fileData;
		my $length = @matched;
		if ($length == 0) {
			print "$target[$i] is not found...\n";
		}
		else {
			print @matched;
		}
	}
}