Windows 从文件中搜索特定行
我有一个数组,其中包含文本文件中的数据 我想筛选数组并将一些信息复制到另一个数组<代码>grep似乎不起作用 这是我的Windows 从文件中搜索特定行,windows,perl,directory,Windows,Perl,Directory,我有一个数组,其中包含文本文件中的数据 我想筛选数组并将一些信息复制到另一个数组grep似乎不起作用 这是我的 $file = 'files.txt'; open (FH, "< $file") or die "Can't open $file for read: $!"; @lines = <FH>; close FH or die "Cannot close $file: $!"; chomp(@lines); foreach $y (@lines){ if
$file = 'files.txt';
open (FH, "< $file") or die "Can't open $file for read: $!";
@lines = <FH>;
close FH or die "Cannot close $file: $!";
chomp(@lines);
foreach $y (@lines){
if ( $y =~ /(?:[^\\]*\\|^)[^\\]*$/g ) {
print $1, pos $y, "\n";
}
}
正则表达式应该将最后一个或两个文件夹放入自己的数组中进行打印。正则表达式对此可能会非常挑剔。将路径拆分为多个组件,然后根据需要进行计数要容易得多。正如在评论中提到的,有一个工具符合您的确切目的,即核心模块 您可以使用它的
splitdir
分解路径,并使用catdir
组合路径
use warnings 'all';
use strict;
use feature 'say';
use File::Spec::Functions qw(splitdir catdir);
my $file = 'files.txt';
open my $fh, '<', $file or die "Can't open $file: $!";
my @dirs;
while (<$fh>) {
next if /^\s*$/; # skip empty lines
chomp;
my @all_dir = splitdir $_;
push @dirs, (@all_dir >= 2 ? catdir @all_dir[-2,-1] : @all_dir);
}
close $fh;
say for @dirs;
使用警告“全部”;
严格使用;
使用特征“说”;
使用File::Spec::Functions qw(splitdir-catdir);
my$file='files.txt';
打开我的$fh,“我无法写出完整的答案,因为我正在使用手机。无论如何,zdim基本上回答了你的问题。但我的解决方案是这样的
use strict;
use warnings 'all';
use feature 'say';
use File::Spec::Functions qw/ splitdir catdir /;
my $file = 'files.txt';
open my $fh, '<', $file or die qq{Unable to open "$file" for input: $!};
my @results;
while ( <$fh> ) {
next unless /\S/;
chomp;
my @path = splitdir($_);
shift @path while @path > 2;
push @results, catdir @path;
}
print "$_\n" for @results;
使用严格;
使用“全部”警告;
使用特征“说”;
使用File::Spec::Functions qw/splitdir catdir/;
my$file='files.txt';
打开我的$fh,'无需重新发明轮子,文件::Spec
来拯救:无需将整个文件复制到@lines
。一个简单的while()
会更好。@Borodin无论如何——我想保留他们的代码。但是,最好改变一些。谢谢,哇。非常感谢您,我将不得不仔细阅读所有的工作原理。@cacartano非常欢迎您:)。是的,仔细阅读模块——它非常简单。如果有任何代码需要解释,请告诉我,我会添加。