griffon vulture
griffon vulture

Reputation: 6764

unix sed - how to replace multilines with regex

I have some file:

aaaaaaaaaa
# Lines Start #
bbbbbbbbb
cccccccc

dddddddddd
# Lines End #
eeeeeeeeee

And some variable $newLines="new line" How can I replace the lines from # Lines Start # to # Lines End # (including those line themselves) with variable's value using sed.

so I'll get:

aaaaaaaaaa
new line
eeeeeeeeee

I've tried using: sed -E 'N; s/# Lines Start #\.*\# Lines End #/$newLines/' But its not doing it's job.

Upvotes: 1

Views: 81

Answers (3)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

var='first line\
second line\
third'
# N.B. multilines must end in "\" except for the last line
sed '/# Lines Start #/,/# Lines End #/c\'"$var" file

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77105

Here is one way with sed:

sed '/# Lines Start #/,/# Lines End #/{
/# Lines End #/!d
s/# Lines End #/new line/
}' file
aaaaaaaaaa
new line
eeeeeeeeee
  • Create a regex range for your pattern
  • If it is not the end of your pattern, delete the pattern space
  • For the line that is the end of your pattern, substitute with new line

Upvotes: 2

Jotne
Jotne

Reputation: 41456

You can use awk if you like to try it:

awk '/# Lines Start #/ {f=1} !f; /# Lines End #/ {print "new line";f=0}' file
aaaaaaaaaa
new line
eeeeeeeeee

You can also use range like in sed, but its less flexible, so I normal avoid the range function.

awk '/# Lines Start #/,/# Lines End #/ {if (!a++) print "new line";next}1' file
aaaaaaaaaa
new line
eeeeeeeeee

Upvotes: 2

Related Questions