gpt4 book ai didi

perl - 搜索文件,当找到匹配时,存储它,然后打印出上面 4 行,下面 3 行

转载 作者:行者123 更新时间:2023-12-01 19:38:50 26 4
gpt4 key购买 nike

我有一个简单的搜索脚本,它接受用户输入并跨目录和文件进行搜索,并仅列出在其中找到的文件。我想要做的是能够在找到匹配项时捕获上面的 4 行它和它下面的 3 行并打印它。所以,假设我有。

somefile.html

"a;lskdj a;sdkjfa;klsjdf a aa;ksjd a;kjaf ;;jk;kj asdfjjasdjjfajsd  jdjd
jdjajsdf<blah></blah> ok ok okasdfa stes test tes tes test test<br>

blah blah blah ok, I vouch for the sincerity of my post all day long.
Even though I can sometimes be a little crass.

I would only know the blue moon of pandora if I saw it. I heard tales of long ago
times in which .. blah blah

<some html>whatever some number 76854</some html>

running thru files of grass etc.. ===> more info
whatever more "

假设我想找到“76854”,它将打印或存储在一个数组中,这样我就可以打印在目录/文件中找到的所有匹配项。

*Match found:*

**I would only know the blue moon of pandora if I saw it. I heard tales of long ago
times in which .. blah blah
<some html>whatever whatever</some html>
running thru files of grass etc.. ===> more info
whatever more**


**********************************

类似的东西。到目前为止,我已经通过打印出找到匹配项的文件来工作:

if ($args->{'keyword'}){
if($keyword =~ /^\d+$/){
print "Your Results are as Follows:\n";
find( sub
{
local $/;
return if ($_ =~ /^\./);
return unless ($_ =~ /\.html$/i);
stat $File::Find::name;
return if -d; #is the current file a director?
return unless -r; # is the file readable?
open(FILE, "< $File::Find::name") or return;
my $string = <FILE>;
close (FILE);
print "$keyword\n";
if(grep /$keyword/, $string){
push(@resultholder, $File::Find::name);
}else{
return;
}
},'/app/docs/');
print "Results: @resultholder\n";
}else{
print "\n\n ERROR\n";
print "*************************************\n\n";
print "Seems Your Entry was in the wrong format \n\n";
print "*************************************\n\n";
}
exit;
}

最佳答案

perl 是这里的先决条件吗?使用 grep 这很容易,您可以告诉它在匹配前后打印 N 行。

grep <search-term> file.txt -B <# of lines before> -A <# of lines after>

如果你真的想用perl,请无视,直接扔掉一个替代品。

关于perl - 搜索文件,当找到匹配时,存储它,然后打印出上面 4 行,下面 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10711191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com