1

How can I use sed to match the search 'pattern' and reuse it again in the 'substitution' part?

Example: I want the command:

echo "12a34" | sed 's/a/#bcd/g'

to return

12abcd34

What should be the # parameter to get the right substitution?

  • 4
    If you mean all pattern in s/pattern/substitusion/ you can recall by & symbol. Thats mean sed 's/a/&bcd/g'. If you'l need just part of pattern you can use back refference: sed 's/\(a\)3/\1bcd/g' – Costas Feb 25 '15 at 14:04
  • Great Costas! solved. – Marcelo Lunardi Feb 25 '15 at 14:18
  • @Costas, see meta.unix.stackexchange.com/a/3927/135943 – Wildcard Apr 15 '16 at 19:27
1

As already commented, the solution is to take the & character in the substitution part:

echo "12a34" | sed 's/a/&bcd/g'

Like this the & is just replaced by the a in the search pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.