[英]Search or find files that contain string or pattern matching
如果不使用任何Perl模塊,是否可以僅用幾行代碼在Perl中執行以下操作?
find . -type f | xargs grep -l "2000.*Created" | cut -c3-100
以上只是給我包含“ 2000. * Created”的文件的文件名。 我想在Perl中執行此操作,並將結果推送到一個數組(文件名數組)中。
我發現Perl File :: Finder模塊具有類似的功能,但是在我當前的工作環境中,我無法訪問或下載任何模塊。
可以用一兩行代碼來完成嗎?
當然可以。
perl -MFile::Find -lwe '
find(sub { -f && push @ARGV, $File::Find::name }, '.');
while(<>) { if (/2000.*Created/) { print substr($ARGV,2); close ARGV; } }'
File::Find
是一個核心模塊,因此它應該已經在您的系統上。 find
子例程將查找所有常規文件,並將其推送到@ARGV
,以便我們可以使用菱形運算符讀取它們。 然后,我們遍歷文件,使用正則表達式檢查內容。 如果找到,我們將打印不帶前2個字符的文件名(我認為這與cut -c3-100
等效)。 close ARGV
線是短路,以防止出現多個匹配項。
對於這個示例,我更喜歡File :: Find -它更加可移植,並且File :: Find可以做一些非常漂亮的事情。 但是,我將提到一種無需內置支持即可用於其他命令的方法。
open F,'find . -type f | xargs grep -l "2000.*Created" | cut -c3-100 |' || die 'cannot execute';
while(<F>) { chomp ; push(@a,$_)}
注意打開的尾隨管道( |
)...這很重要,因為Perl會自動為您完成所有連接管道的工作。
這也可以使用更新的3參數open來編寫:
open my $fh, '-|', 'find . -type f | xargs grep -l "2000.*Created" | cut -c3-100' || die 'cannot execute';
while(<$fh>) { chomp ; push(@a,$_)}
作為旁注, find | xargs
如果文件名帶有空格, find | xargs
將會出現一些問題。 您可以解決,與-print0
行動find
和-0
的標志xargs
:
find . -type f -print0 | xargs -0 -l "2000.*Created" | cut -c3-100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.