我正在尋找一個 perl 腳本來 grep 目錄內所有檔案中的字串。
bash 命令。代碼:
grep -r 'word' /path/to/dir
uj5u.com熱心網友回復:
這是一項相當規范的任務,而我無法使用可能最簡單的工具找到直接的答案,即方便的Path::Tiny
use warnings;
use strict;
use feature 'say';
use Data::Dump; # dd
use Path::Tiny; # path
my $dir = shift // ".";
my $pattern = qr/word/;
my $ret = path($dir)->visit(
sub {
my ($entry, $state) = @_;
return if not -f;
for ($entry->lines) {
if (/$pattern/) {
print "$entry: $_";
push @{$state->{$entry}}, $_;
}
}
},
{ recurse => 1 }
);
dd $ret; # print the returned complex data structure
在此處讀取檔案的方式,使用lines, 只是實作此目的的一種方式。它可能不適合非常大的檔案,因為它一次讀取所有行,最好逐行讀取。
該visit方法基于iterator,它也干凈地完成了這項任務
my $iter = path($dir)->iterator({ recurse => 1 });
my $info;
while (my $e = $iter->()) {
next if not -f $e;
# process the file $e as needed
#/$pattern/ and push @{$info->{$e}}, $_ and print "$e: $_"
# for $e->lines
}
在這里,我們必須提供一個資料結構來積累資訊,但我們獲得了更大的靈活性。
否則,有用于遞回遍歷和搜索的庫,例如File::Find(或File::Find::Rule)或Path::Iterator::Rule
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489481.html
