1

I've searched all over stackoverflow (perhaps I just suck at searching) but I cannot find the answer to my problem. I'm trying to insert a word or a string in between two patterns in the same line using sed.

I know how to insert a word AFTER a searched pattern using

sed -e "s/pattern/& new_word/g"

with an ampersand (&).

But this command inserts 'new_word' in every occurrence of searched pattern so I'm trying to specify it so that it inserts 'new_word' only in between two patterns.

For example,

Some words  = [want to insert words here];

How do I insert it between "Some words (multiple whitespaces here) =" and ";"?

What is the syntax for this kind of command? Also, what resources do you guys use to learn sed? Many of the sed tutorials that I've searched are very basic and doesn't go into details of usage of different options and flags.

Thank you.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

2

Use capture groups.

sed -e 's/(pattern1)(pattern2)/\1new_word\2/'

\1 is replaced with whatever matched the first pattern, \2 gets whatever matched the second pattern.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you! That worked but I had to use double quotes. What is the difference between using single quotes and double quotes? Also, I had to use the back slash before parentheses like this sed -e "s/\(something\)\(;\)/\1new_word\2/" – Sweetfinish Oct 16 '19 at 21:05
  • You shouldn't need double quotes unless you have variables in the pattern or replacement. – Barmar Oct 16 '19 at 21:08
  • https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash – Barmar Oct 16 '19 at 21:08