Perl,如何从这个完整路径获取目录路径?

时间:2012-12-19 02:43:07

标签: regex perl

  

可能重复:
  Given the full path to a file, how do I get just the path without the filename?

我的完整路径可以有这些类型的模式。我怎样才能获得目录路径?

file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\d_param_ZRK176E
file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_HCB@002.txt
file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_QCB@B006.1.txt

由于 冯吉荣

2 个答案:

答案 0 :(得分:1)

如前所述,您可以使用许多CPAN模块,这意味着您可以避免进行字符串操作。 E.g。

use File::Basename 'fileparse';

my @files = qw(
    file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\d_param_ZRK176E
    file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_HCB@002.txt
    file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_QCB@B006.1.txt
);

my @dirs = map { (fileparse($_))[1] } grep { s/^file=// } @files;
print join "\n", @dirs;

答案 1 :(得分:0)

这会解决您的问题

my @list = qw(
  file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\d_param_ZRK176E
  file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_HCB@002.txt
  file=M:\ccadm01_IACB_DEV\Informatica_AVOB\IACB_src\parm\p_param_QCB@B006.1.txt
);

for my $line (@list) {
  my @split_path =  split(/\\/, $line);
  for my $i (1..$#split_path) {
    print @split_path[$i], "/";
  }
  print "\n";
}