如何使用Perl修改文件,在双引号之间添加和替换字符串

时间:2012-04-28 19:27:47

标签: perl

如何在以下两种情况下使用Perl修改文件(以下内容作为其内容的一部分)。字符串的正确位置(从第一行写入2个空格的正确行)很重要。此外,在以下TEST中,$ {P} / TEST不是恒定的并且在运行期间会发生变化;所以我们不应该使用匹配函数。 原始文件是:

! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/TEST"
  ## widget = uniline

1)添加另一个带双引号的字符串,正好在“$ {P} / TEST”下,例如“$ {P} / XXXXXX”(XXXXXX在程序之前定义)。注意活动的数量! 所以它会变成:

! List of Campaigns
! -----------------
CAMPAIGN 2
  "${P}/TEST"
  "${P}/XXXXXX"
  ## widget = uniline

2)替换“$ {P} / XXXXXX”而不是“$ {P} / TEST”。 所以它会变成:

! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/XXXXXX"
  ## widget = uniline

1 个答案:

答案 0 :(得分:0)

这应该会给你一个想法。我看到了add_campaignreplace_campaign操作的必要性,然后从那里开始。您的数据位于__DATA__伪文件中。

节目输出:

$ campaigns.pl
! List of Campaigns
! -----------------
CAMPAIGN 3
  "${P}/TEST"
  "${P}/MONKEY"
  "${P}/BLUE"
  ## widget = uniline

节目来源:

#!/usr/bin/perl

use strict;
use warnings;

### main program

# read entire file contents into $data
my $data = do { local $/; <DATA> };

# make an entry in %campaigns for each campaign in $data. Each entry's key 
# is the campaign's name. Its value is irrelevant. We use 1.
my %campaigns;
my $last_campaign_offset;   # index of last campaign found
while ( $data =~ /  "\$\{P\}\/(\w+)"/g ) {
  $campaigns{$1}        = 1;
  $last_campaign_offset = index($data, $');
}

add_campaign('CAMEL');
add_campaign('BLUE');
add_campaign('TEST');   # no-op: campaign already exists
replace_campaign('CAMEL', 'MONKEY');
print $data;


### subroutines

### append a new '  ${P}/FOO' campaign to the data
sub add_campaign {
  my $new_cpn = shift;
  return if exists $campaigns{$new_cpn};

  $new_cpn = qq[\n  "\${P}/$new_cpn"];
  substr($data, $last_campaign_offset) 
    = $new_cpn . substr($data, $last_campaign_offset);
  $last_campaign_offset += length($new_cpn);

  # lastly, increment n in the "CAMPAIGN n" substring
  $data =~ s/(?<=CAMPAIGN )(\d+)/$1 + 1/e;
}

### replace the name of an existing campaign with a new one
sub replace_campaign {
  my ($old_cpn, $new_cpn) = @_;
  $data =~ s/(?<=  "\$\{P\}\/)$old_cpn/$new_cpn/;
}


__DATA__
! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/TEST"
  ## widget = uniline