gpt4 book ai didi

string - 读取搜索字符串的文件并打印其路径

转载 作者:行者123 更新时间:2023-12-04 05:42:34 25 4
gpt4 key购买 nike

我正在尝试在 Perl 中编写一个在特定目录和所有子目录中搜索的脚本。这样做的目的是脚本必须读取目录和所有子目录中的所有文件,以寻找特定的文本字符串(我定义的任何字符串)。如果在文件中找到该字符串,则脚本将在新文本文件中打印文件的路径和名称,并继续处理目录树中的所有文件。

我有这样的事情,但我不确定如何继续。我是 Perl 的初学者,对所有选项一无所知。

#!/usr/bin/perl
use strict;
use File::Find;

my $dir = 'C:\PATH\TO\DIR';
my $string = "defined";

find(\&printFile, $dir);
sub printFile {
my $element = $_;
open FILE, "+>>Results.txt";
if(-f $elemento && $elemento =~ /\.txt$/) {
my $boolean = 0;
open CFILE, $elemento;
while(<CFILE>) {
if ($string) {
print FILE "$File::Find::name\n";
}
close CFILE;
}
}
close FILE;
}

sleep(5);

最佳答案

你离得不远了,但是有些事情你需要改变。

#!/usr/bin/perl
use strict;
use warnings; # never go without warnings
use File::Find;

my $dir = 'C:\PATH\TO\DIR';
my $string = "defined";
open my $out, ">>", "Results.txt" or die $!; # move outside, change mode,
# 3-arg open, check return value
find(\&printFile, $dir);

sub printFile {
my $element = $_;
if(-f $element && $element =~ /\.txt$/) { # $elemento doesn't exist
open my $in, "<", $element or die $!;
while(<$in>) {
if (/\Q$string\E/) { # make a regex and quote metachars
print $out "$File::Find::name\n";
last; # stop searching once found
}
}
} # lexical file handles auto close when they go out of scope
}

更好的是放弃硬编码值并跳过特定的输出文件:
my $dir = shift;
my $string = shift;

然后只需将输出打印到 STDOUT。
print "$File::Find::name\n"; 

用法:
perl script.pl c:/path/to/dir > output.txt

正如其他人在评论中指出的那样,这可以通过递归 grep 轻松解决。 .但不幸的是,您似乎使用的是 Windows,在这种情况下,它不是一种选择(据我所知)。

关于string - 读取搜索字符串的文件并打印其路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102657/

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