0

我正在寻找脚本中的文件路径。所以我要写一个脚本,找出文件然后寻找“/”。

我宁愿使用 perl 正则表达式,只想 grep 出文件路径。

foo@foohost:~ $ cat /sbcimp/dyn/data/FOO/GSD/scripts/FOOonoff.pl | grep "/"

#!/usr/bin/perl
my $output_file = "/sbcimp/dyn/data/stmFOO3/dailymetrics/PartRates/file6.csv";
my $input_file_name_ESTATE = "/sbcimp/dyn/sym/data/stmFOO3/part_rates/FOO_estate.$year$month1$day1.1630.csv";
my $input_file_name_ESTATE = "/sbcimp/data/stmFOO3/part_rates/FOO_estate.20140829.1630.csv";
my $input_file_name_ESTATE2 = "/sbcimp/part_rates/FOO_estate.$year$month1$day2.1630.csv";
my $input_file_name_ESTATE3 = "/sbcimp/FOO_estate.$year$month2$day3.1630.csv";
my $input_file_name_NEW = "/sbcimp/dyn/data/stmFOO3/dailymetrics/RiskTiers/new_terms.csv";
    $argVal =~ s/\s+$//;
    $argVal =~ s/^\s+//;
    $argVal =~ s/\"$//;
    $argVal =~ s/^\"//;
    $argVal =~ s/\'$//;
    $argVal =~ s/^\'//;

如果我整理出文件并将其放入 perl one 衬里,我只会得到根目录。

foo@foohost:~ $ cat /sbcimp/dyn/data/FOO/GSD/scripts/FOOonoff.pl | perl -nle 'print /(\/\w+\/)/' | sort -u

/sbcimp/

我理解正则表达式中的量词,但如果我使用 'print /(/\w+/){1,9}/' 那不会给我 "/w+/.. 1 或 9 次。我要找对于距离根路径 1 次或多次的路径。如何量化整个捕获的正则表达式,而不仅仅是最后一个字符?

4

1 回答 1

3

我建议不要使用正则表达式来解析 Perl 代码,而是使用PPI.

下面解析您为字符串提供的 perl 行,将它们简化为它们的基本内容,然后提取路径信息:

use strict;
use warnings;

use PPI;
use File::Basename;

my $src = do {local $/; <DATA>};

# Load a document
my $doc = PPI::Document->new( \$src );

# Find all the strings within the doc
my $strings = $doc->find( 'PPI::Token::Quote' );
for (@$strings) {
    my $str = eval 'no strict; no warnings; '. $_->content;
    next if $@ || $str !~ /\//;

    my ($name, $path) = fileparse($str);

    print "$path\n";
}

__DATA__
#!/usr/bin/perl
my $output_file = "/sbcimp/dyn/data/stmFOO3/dailymetrics/PartRates/file6.csv";
my $input_file_name_ESTATE = "/sbcimp/dyn/sym/data/stmFOO3/part_rates/FOO_estate.$year$month1$day1.1630.csv";
my $input_file_name_ESTATE = "/sbcimp/data/stmFOO3/part_rates/FOO_estate.20140829.1630.csv";
my $input_file_name_ESTATE2 = "/sbcimp/part_rates/FOO_estate.$year$month1$day2.1630.csv";
my $input_file_name_ESTATE3 = "/sbcimp/FOO_estate.$year$month2$day3.1630.csv";
my $input_file_name_NEW = "/sbcimp/dyn/data/stmFOO3/dailymetrics/RiskTiers/new_terms.csv";
    $argVal =~ s/\s+$//;
    $argVal =~ s/^\s+//;
    $argVal =~ s/\"$//;
    $argVal =~ s/^\"//;
    $argVal =~ s/\'$//;
    $argVal =~ s/^\'//;

输出:

/sbcimp/dyn/data/stmFOO3/dailymetrics/PartRates/
/sbcimp/dyn/sym/data/stmFOO3/part_rates/
/sbcimp/data/stmFOO3/part_rates/
/sbcimp/part_rates/
/sbcimp/
/sbcimp/dyn/data/stmFOO3/dailymetrics/RiskTiers/
于 2014-09-04T04:35:36.747 回答