Geek Geek - 9 days ago 6
Bash Question

Can we use regex within sed

I have a sample file with many sections. There can be multiple new lines within a section. So, we can encounter multiple new lines (\n) within a section.

Section1

Section2
(
(a) (b)
(c) (d)
(e) (f)
))

Section 3


I want to replace all the contents of Section 2 with some other content. So, one thing I am aware is that section closes with consecutive ) brace. Is there a way I can do it via a
sed
using regex. I want to do it via only shell script only.

I know I can give

sed/findpattern/replacementtext/g


How do I add a
regex
here to populate
findpattern
. Can I give a full fledged regex here?

Expected Output

Section1

Section2
(
(m) (n)
(o) (p)
(q) (r)
))

Section 3


Only Section 2 contents need to be found first and then it needs to be replaced with some content like above.

Answer

With the c(change) command:

sed '
/Section2/,/))/c \
    Section2 \
    ( \
        (m)   (n) \
        (o)   (p) \
        (q)   (r) \
    ))
' file