问题描述
是否可以在同一命令中将乘法模式更改为不同的值?假设我有
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...
谢谢!
推荐答案
Easy in Perl:
Easy in 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
/($re)/
# or
/^($re)$/
# resp.
这篇关于替换多个模式,但不要使用相同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!