1

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.

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

1 Comment

c \ replaces the selected lines with the text. The only caveat that potong rightly stated in his answer is if you use a variable with embedded new lines then they must be preceded by a backslash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.