从文件中搜索特定行 [英] Search for specific lines from a file

查看:88
本文介绍了从文件中搜索特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含文本文件中的数据。

I have an array that contains the data from a text file.

我想过滤数组并将某些信息复制到另一个数组。 grep 似乎无法正常工作。

I want to filter the array and copy some information to another array. grep seems to not work.

这就是我所拥有的

$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";
    }
}



files.txt



files.txt

public_html
Trainings and Events
General Office\Resources
General Office\Travel
General Office\Office Opperations\Contacts
General Office\Office Opperations\Coordinator Operations
public_html\Accordion\dependencies\.svn\tmp\prop-base
public_html\Accordion\dependencies\.svn\tmp\props
public_html\Accordion\dependencies\.svn\tmp\text-base

正则表达式应使用最后一个或两个文件夹,并将它们放入自己的数组中进行打印。

The regular expression should take the last one or two folders and put them into their own array for printing.

推荐答案

正则表达式对此非常挑剔。将路径拆分为多个组件,然后根据需要分配数量要容易得多。核心模块 File: :规范 ,如 xxfelixxx 在评论中所述。

A regex can get very picky for this. It is far easier to split the path into components and then count off as many as you need. And there is a tool that fits your exact purpose, the core module File::Spec, as mentioned by xxfelixxx in a comment.

您可以使用其 splitdir 中断路径,并使用 catdir 组成一个。

You can use its splitdir to break up the path, and catdir to compose one.

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;

我使用该模块的功能接口,而对于繁重的工作,则需要其面向对象的接口。将整个文件读入数组有其用途,但通常是逐行处理。可以更优雅地完成列表操作,但我还是为了简单起见。

I use the module's functional interface while for heavier work you want its object oriented one. Reading the whole file into an array has its uses but in general process line by line. The list manipulations can be done more elegantly but I went for simplicity.

我想添加一些一般性评论

I'd like to add a few general comments


  • 始终使用使用严格使用警告启动程序

使用词汇文件句柄,我的$ fh 而不是 FH

Use lexical filehandles, my $fh instead of FH

了解(至少)一打或两个最常用的模块是真的很有帮助。例如,在上面的代码中,我们甚至不必提及分隔符 \

Being aware of (at least) a dozen-or-two of most used modules is really helpful. For example, in the above code we never had to even mention the separator \.

这篇关于从文件中搜索特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆