[英]perl regex for multiple matches
I have a file with lines similar to following: 我有一个与以下内容相似的文件:
abcd1::101:xyz1,user,user1,abcd1,pqrs1,userblah,abcd1
I want to retain strings up to last ":" and remove all occurrences of abcd1 我想保留字符串直到最后的“:”并删除所有出现的abcd1
In the end, I need to have below: 最后,我需要具备以下条件:
abcd1::101:xyz1,xyz2,xyz3,pqrs1,xyz4
I tried code as below, but for some reason, it is not working. 我尝试了如下代码,但是由于某种原因,它无法正常工作。 So please help the account name is "abcd1"
因此,请帮助帐户名称为“ abcd1”
sub UpdateEtcGroup {
my $account = shift;
my $file = "/tmp/group";
@ARGV = ($file);
$^I = ".bak";
while (<>){
s#^($account::\d{1,$}:)$account,?#$1#g;
s/,$//; # to remove the last "," if there
print;
}
}
Don't use a regular expression for this. 请勿为此使用正则表达式。
use strict;
use warnings;
while (<DATA>) {
chomp;
my @parts = split(/:/, $_);
$parts[-1] = join(',', grep { !/^abcd/ } split(/,/, $parts[-1]));
print join(':', @parts) . "\n";
}
__DATA__
abcd1::101:xyz1,user,user1,abcd1,pqrs1,userblah,abcd1
abcd2::102:user1,xyz2,otheruser,abcd2,pqrs1,xyz4,abcd2
Output: 输出:
abcd1::101:xyz1,user,user1,pqrs1,userblah
abcd2::102:user1,xyz2,otheruser,pqrs1,xyz4
split
is the tool for the job, not a regex
. split
是工作的工具,而不是regex
。
Because split
lets you reliably separate out the field you do want to operate on, from the ones that you don't. 因为
split
使您可以可靠地将您要操作的字段与不需要的字段分开。 Like this: 像这样:
#!/usr/bin/env perl
use strict;
use warnings;
my $username = 'abcd1';
while ( <DATA> ) {
my @fields = split /:/;
my @users = split ( /,/, pop ( @fields ) );
print join ( ":", @fields,
join ( ",", grep { not m/^$username$/ } @users ) ),"\n";
}
__DATA__
abcd1::101:xyz1,user,user1,abcd1,pqrs1,userblah,abcd1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.