开发者

Need to replace part of a string with another string

开发者 https://www.devze.com 2023-04-11 00:33 出处:网络
I\'m still pretty new to perl and regex and need some help getting started.I would love to provide some code, but that\'s kinda where I\'m stuck.

I'm still pretty new to perl and regex and need some help getting started. I would love to provide some code, but that's kinda where I'm stuck.

What I'm trying to do is that I have this string in a file like this:

dn: CN=doe\, john,OU=Users,DC=domain,DC=com

and a string like this:

uid: d12345

I need to do a search and replace to get the following result.

dn: uid= d12345,OU=Users,DC=domain,DC=com

Can anyone help me get started with this one开发者_如何学Python? Much thanks!


So you want to replace CN=doe\, john with uid= d12345? Try this:

$uidString = "uid: d12345";
$dnString = "dn: uid= d12345,OU=Users,DC=domain,DC=com";

if( $uidString =~ /uid: (\w+)/ ) {
  $uid = $1;
  $dnString =~ s/CN=.+?[^\\],/uid= $uid,/;
}

That will replace everything from CN= to the first unescaped comma with the uid.


Won't a one line regex do the trick?

use strict;
use warnings;

my $a = "dn: CN=doe\, john,OU=Users,DC=domain,DC=com";
my $b= "uid: d12345";
#the regex
$a =~ s/CN(.*?), .*?,/$b,/;

print "$a";


I suspect your DNs and uids will be dynamic. Here is something that will help. The regex will substitute CN= all the way until the comma with whatever string you put in $uid.

#!/usr/bin/env perl

use strict;
use warnings;

my $string = 'dn: CN=doe\, john,OU=Users,DC=domain,DC=com';
my $uid_str  = 'uid: d12345';
my ($uid) = $uid_str =~ m/^uid:(.+)$/;
$string =~ s/CN=.+(,OU=.+$)/uid=$uid$1/;

print "String is: $string\n";

Output: String is: dn: uid= d12345,OU=Users,DC=domain,DC=com

0

精彩评论

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