替换多个模式,但不能用相同的字符串 [英] Replace multiple patterns, but not with the same string
问题描述
是否可以在同一命令中将乘法模式更改为不同的值?可以说我有
is it possible to change multiply patterns to different values at the same command? lets say I have
A B C D ABC
我想将每个A更改为1,将每个B更改为2,将每个C更改为3
and I want to change every A to 1 every B to 2 and every C to 3
所以输出将是
1 2 3 D 123
由于我要更改3种模式,因此我希望避免单独替换它们.我以为会有
since I have 3 patterns to change I would like to avoid substitute them separately. I thought there would be something like
sed -r s/'(A|B|C)'/(1|2|3)/
但是当然这只是将A或B或C替换为(1 | 2 | 3).我只想提一下,我的真实模式比这还要复杂...
but of course this just replace A or B or C to (1|2|3). I should just mention that my real patterns are more complicated than that...
谢谢!
推荐答案
在Perl中很简单:
perl -pe '%h = (A => 1, B => 2, C => 3); s/(A|B|C)/$h{$1}/g'
如果使用更复杂的模式,则在替代列表中将更具体的模式放在更一般的模式之前.按长度排序可能就足够了:
If you use more complex patterns, put the more specific ones before the more general ones in the alternative list. Sorting by length might be enough:
perl -pe 'BEGIN { %h = (A => 1, AA => 2, AAA => 3);
$re = join "|", sort { length $b <=> length $a } keys %h; }
s/($re)/$h{$1}/g'
要添加单词或行边界,只需将模式更改为
To add word or line boundaries, just change the pattern to
/\b($re)\b/
# or
/^($re)$/
# resp.
这篇关于替换多个模式,但不能用相同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!