Reputation: 1535
How can I use sed
so that when it finds a match, I can use it in the substitution field?
For example
echo "12a34" | sed 's/a/#bcd/g'
12abcd34
What do I replace the #
with to get the expected result?
Upvotes: 0
Views: 247
Reputation: 44043
Use &
:
echo '12a34' | sed 's/a/&bcd/g'
12abcd34
&
in the replacement clause of a s///
command refers to what the pattern matched, which is the a
in this case.
This particular case doesn't show very well how it works, since a
is not a very interesting regular expression, so let me add a better example:
echo foobar | sed 's/[fb]/&42/g'
f42oob42ar
where the f
and the b
are matched by [fb]
and subsequently replaced with f42
and b42
.
Upvotes: 4