Perl Regex用于从文件中获取版本号

时间:2012-12-06 21:07:49

标签: regex perl

我有一个如下所示的文件:

app.version.code=1
app.version.major=1
app.version.minor=0
app.version.buildnumber=0

我想运行一个打印出<app.version.major>.<app.version.minor>.<app.version.buildnumber>的Perl脚本。在这种情况下,它将打印出1.0.0。我现在对Perl非常生疏,并且无法创建一个正则表达式和脚本来给我这个。有什么想法吗?

5 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

perl -F= -lane '$h{$F[0]}=$F[1]; 
  END { print join ".", @h{ glob "app.version.{major,minor,buildnumber}" } }' filename

答案 1 :(得分:1)

cat > ver.txt
app.version.code=1
app.version.major=1
app.version.minor=0
app.version.buildnumber=0
^d

cat> ver.pl
#!/usr/bin/perl -w

use strict;
use warnings;

my ($ma,$mi,$bi)=(0,0,0);
while(<>){ 
  if(/^app\.version\.(.*)$/) { 
    if( $1 =~ /^major=(\d+)$/ ){$ma=$1}
    elsif( $1 =~ /minor=(\d+)$/ ){$mi=$1}
    elsif( $1 =~ /buildnumber=(\d+)$/ ) {$bi=$1}
  }
} 

print "$ma.$mi.$bi\n";
^d

./ver.pl < ver.txt 
1.0.0

答案 2 :(得分:0)

VersionXtrct.pl:

    #!/usr/bin/perl

    use strict;

    my $inFile = $ARGV[0];

    open(INHANDLE, "<$inFile") || die("Could not open file");

    my @fileLines = <INHANDLE>;

    my $fileText = join("", @fileLines);

    my $major;
    my $minor;
    my $build;

    if($fileText =~ m/app\.version\.major=(.+)\n/) { $major = $1; }

    if($fileText =~ m/app\.version\.minor=(.+)\n/) { $minor = $1; }

    if($fileText =~ m/app\.version\.buildnumber=(.+)\n/) { $build = $1; }

    my $version = $major.".".$minor.".".$build;

print "\nversion = ".$version;

    exit(0);

假设您的数据位于名为input.txt的文件中,请运行:

VersionXtrct.pl input.txt

答案 3 :(得分:0)

我在之前的尝试中假设了非任意顺序。这应该按预期工作。

#!/usr/bin/env perl

use strict;
use warnings;

use 5.010;

my %version;

while (<DATA>) {
  given ($_) {
    $version{major}       = $1 when /app\.version\.major=(\d+)/;
    $version{minor}       = $1 when /app\.version\.minor=(\d+)/;
    $version{buildnumber} = $1 when /app\.version\.buildnumber=(\d+)/;
  }
}

say join ".", @version{qw/major minor buildnumber/};

__DATA__
app.version.code=1
app.version.major=1
app.version.minor=0
app.version.buildnumber=0

答案 4 :(得分:0)

这是另一种选择:

use strict;
use warnings;

my %ver;

while (<>) {
    $ver{$1} = $2 if /(major|minor|number)=(\d+)$/;
}

print "$ver{major}.$ver{minor}.$ver{number}\n";

数据集输出:

1.0.0