开发者

Perl/Regex: Edit a line in a file

Essentially I want to create a script to deploy a database connection script to host SVN branches.

The template file looks something like

//comments
//comments
//comments
//$db="user:pass@host/###branchdb###";
//other stuff

Basically I want to:

  1. Find the line by ###branchdb###
  2. Remove the commenting at the start of the line '//'
  3. Replace the ###branchdb### with a script argument

The script is Perl based, so I guess I'd like to accomplish this task using Perl, although I understand that Bash/Linux Environment provides plenty of tools to accomplish this as well, so if I need to use those then so be it.

I'm also assuming I'll need to use some amount of regex for this? Perhaps not, however I'd certainly like to as regex is a constant point of failure for me so the more excu开发者_运维问答ses I can get to try and get my head around it the better :)

Thanks for any help!

Full Solution with Wes's help below:

open IN, $sourceFile or die "Can't open $sourceFile";
open OUT, ">$destinationFile" or die "Can't write to $destinationFile";

while(<IN>) {
  if ($_ =~ m/%BRANCH_DB%/) {
    $_ =~ s!^\s*//!!;
    $_ =~ s/%BRANCH_DB%/$branch/;
  }
  print OUT $_;
}

close(IN);
close(OUT);

Also I changed ###branchdb### to %BRANCH_DB% as I was advised this is a more common placeholder.


$_ =~ s/\/\/(.*)###branchdb###/\1$arg/


From the command line directly.

(ol)noufal@sanitarium% more test
//comments
//comments
//comments
//$db="user:pass@host/###branchdb###";

(ol)noufal@sanitarium% perl -p -i -e 's!^//(.*)###branchdb###!$1mynewbranchname!g' test
(ol)noufal@sanitarium% more test
//comments
//comments
//comments
$db="user:pass@host/mynewbranchname";
//other stuff
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜