如何在Perl中修改复杂的命令行参数字符串?

时间:2010-03-25 20:44:22

标签: regex perl

我有一个命令行,我正在尝试修改以删除一些参数。这种复杂的原因是我可以拥有嵌套的参数。

说我有这个:

$cmdline = "-a -xyz -a- -b -xyz -b- -a -xyz -a-"

我有三个不同的-xyz标志,它们将在两个不同的上下文中解释。一个是-a上下文,另一个是-b上下文。

我想删除“a”-xyz,但将其保留在“b”-xyz中。

在上述情况下,我想:

-a -a- -b -xyz -b- -a -a-

或者,如果我有:

-a -123 -a- -b -xyz -b- -a -xyz -a-"

我想:

-a -123 -a- -a -xyz -a- -b -xyz -b- -a -a-

这是我坚持的第二个案例。

如何在Perl中最有效地执行此操作?

3 个答案:

答案 0 :(得分:2)

use strict;
use warnings;

my @cmds = (
    '-a -123 -a- -b -xyz -b- -a -xyz -a-',
    '-a -xyz -a- -b -xyz -b- -a -xyz -a-',
);

for my $c (@cmds){
    # Split command into parts like this: "-a ... -a-"
    my @parts = $c =~ /( -\w\s .+? -\w- )/gx;
    for my $p (@parts){
        $p =~ s{-xyz\s+}{} if $p =~ /^-a/;
    }
    # The edited command line consists of the joined parts.
    print "@parts\n";
}

答案 1 :(得分:1)

#!/usr/bin/perl -w
sub replace_in_ctx {
  my $cmdline = shift;
  my @result = ();
  for (split / /, $cmdline) {
    push @result, $_ unless /-a/../-a-/ and /^-xyz$/;
  }
  return join " ", @result;
}
# first case
print replace_in_ctx("-a -xyz -a- -b -xyz -b- -a -xyz -a-") . "\n";

# second case
$_ = replace_in_ctx("-a -123 -a- -b -xyz -b- -a -xyz -a-");
s/-a -123 -a-/$& -a -xyz -a-/;
print "$_\n";

运行它:

$ perl match_context.pl 
-a  -a- -b -xyz -b- -a  -a-
-a -123 -a- -a -xyz -a- -b -xyz -b- -a  -a-

答案 2 :(得分:0)

如果我理解正确,则上下文以-a开头,以-a-结尾。

use warnings; use strict;

my $cmdline = "-a -123 -a- -b -xyz -b- -a -xyz -a-";
$cmdline =~ s/( ?-a) +-xyz +(-a- ?)/$1 $2/g;

print "$cmdline\n";